In MVC model, we have to declare a key field as Id or EntityNameId. What is the significance of it? Can I declare a key field with any name I wish ?
2 Answers
Assuming this is for Entity Framework, You can decorate any field within your models with the [Key] attribute.
public class Student {
[Key]
public int StudentRegNumber { get;set; }
}
However I am sure it's best practice to keep Id in the name for use in EntityFramework simply because it does all the property mapping for you. If you want to go a step further and manage this primary key yourself (not recommended) and make it not auto increment you can use this attribute as well
[DatabaseGenerated(DatabaseGeneratedOption.None)]
But ideally, as I mentioned before you are going to want to keep Id in the name, so let's go with this instead.
public class Student {
public int StudentId { get; set; }
public int RegNumber { get; set; }
}
Since EF is smart enough to map the Key automatically utilise that sweet sweet power!
Extended
Mackan suggested explaining the importance. If we start changing our Primary Key names to not follow the convention of suffixing then name with 'Id' and rather just leaving them to be anything, it can become confusing when building up queries later on, or doing Joins on your datasets etc.
However it's best to make a choice and stick to one type of naming convention, there is a debate (1 & 2) as to whether it's actually bad practice to do TableNameId instead of just Id, however that is for you to decide what works best for you, but I would recommend away from just naming them something unrelated to their primary purpose; the unique identification of that record.
Further Reading
-
1Swift answer! For completeness, perhaps you'd want to add something in regards to "What is the significance of it?" (ie. primary key and so on) – Mackan Apr 14 '15 at 07:57
-
Added some stuff in, however I am not really that much of a Db guy - hope what I provided is ok – JEV Apr 14 '15 at 08:05
-
1Ah, I was rather thinking of the "significance" of using the `key annotation` at all, not what naming convention to use. A matter of interpretation I guess :) Nice work anyway. – Mackan Apr 14 '15 at 08:09
-
1@Glitch100 Thank you for your answer with detailed information ! It helped. – user3077222 Apr 14 '15 at 08:56
-
@user3077222 If this is the answer please mark it as such so others can find it with ease – JEV Apr 14 '15 at 09:00
Entity Framework Code first relies on every entity having a key value that it uses for tracking entities. One of the conventions that code first depends on is how it implies which property is the key in each of the code first classes. That convention is to look for a property named “Id” or one that combines the class name and “Id”, such as “BlogId”. The property will map to a primary key column in the database. See link https://msdn.microsoft.com/en-us/data/jj591583.aspx

- 9,190
- 36
- 114
- 202