Reputation: 99
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 ?
Upvotes: 0
Views: 1844
Reputation: 2504
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
Data Annotations in Entity Framework
Entity Framework Code First Conventions
Upvotes: 2
Reputation: 9416
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
Upvotes: 0