Reputation: 1457
I am new to ASP.Net MVC and I am trying to get a better understanding of ASP.Net MVC. I did a couple tutorials and made a few models in those tutorials. One question that kept popping up in my head was: When would I use public int Id { get; set; }
and when would I be using public int MyClassNameId { get; set; }
instead as identifier for my model class? Would it matter if I would use a custom property name instead of the default Id
name for my identifier for a model class?
For example, why would I use public int ArtistId { get; set; }
over public int Id { get; set; }
?:
public class Artist
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
Is it so that it matches a property name in another class in which it will be used as Foreign Key?
Upvotes: 1
Views: 2847
Reputation: 11
This depends on whether or not using Entity Framework to set up your databases. If you are Entity Framework looks for specific property names to identity as Primary Keys.
For example, let's say you have a model called Book.
public class Book
{
public string Title {get; set;}
//all other properties here
}
When Entity Framework tries to set up your database, it looks for a property that it can identify as a primary key corresponding to the specific model. In this case EF would look for "BookID" as a primary key. So if you wished to have an accessible primary key property you would set it up like this.
public class Book
{
public int BookID {get;set;}
public string Title {get; set;}
//all other properties here
}
If you wished to set up a primary key that was not called "BookID", you could use a data annotation:
public class Book
{
[Key]
public int BookIdentifier{get;set;}
public string Title {get; set;}
//all other properties here
}
Upvotes: 0
Reputation: 7706
Entity Framework CodeFirst recognize the key, by default, by name. Valid names are Id
or <YourClassName>Id
.
Your property should be named Id
or AccountTypesId
Another way is to use the ModelBuilder
to specify the key.
Sample
public class MyDbContext : DbContext
{
public DbSet<Artists> Artists{ get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Artists>.HasKey(x => x.ArtistId);
base.OnModelCreating(modelBuilder);
}
}
More about it you can find here
Upvotes: 2
Reputation: 103
If you use custom property names then compiler will not understand it's meaning that it is an id and must be used as primary key in database table. when you name it id compiler understands it's meaning .
Upvotes: 0