Hello I am coding in MVC 3, using C#.
I am populating an Associating table between a tutor and a student, called Tutor_Student. the Primary Key of this table consists of the tutorId and studentId, from the parent tables, and Subject.
what i have in my Model is as follows:
[Key, Column(Order = 0)]
public string tutorID { get; set; }
[Key, Column(Order = 1)]
public string studentID { get; set; }
[Key, Column(Order = 2)]
public string Subject { get; set; }
When the user populates this table from the website I want to ensure that the composite primary key does not already exist in the database to avoid primary key violations.
Is there any way of doing this?
Thank you in advance, i really appreciate it…
One way to handle this is to have a
unique constrainton the columns and let SQL Server handle the validation. Then you can justcatchtheSqlExceptionthrown when saving and handle it gracefully. The SqlException class contains lots of useful information that you can dig into to figure out what went wrong, like theErrorscollection.Another way to deal with this is to create a data access layer that contains helper methods for these sorts of things. In the repository pattern, a data Repository is a natural place to have the following method:
The exact implementation of this method depends on your database server and such, but by following the repository pattern, you get the required level of separation in your application to deal with these types of problems in a structured and intuitive way.