bb2
bb2

Reputation: 23

Primary key has to be called "Id" using EFCode?

I'm writting an application using ASP MVC 3 and based on the music store tutorial. I installed the EFCode framework and I created a database by right clicking App_Data folder. The columns of the Table "Client" are IdClient Name

IdClient was defined as primary key by right clicking on it, and Identity was set to Yes and autoincrement, etc. Everything seems fine...When I run the application it tells me that this table has no key defined!!

If i rename IdClient to Id there is no problem, my question why doesn't it detect IdClient as primary key?? In the tutorial database the primary keys are not defined with a name "Id"...

Thanks!

Upvotes: 2

Views: 1987

Answers (2)

Chad Moran
Chad Moran

Reputation: 12854

I assume you mean Entity Framework Code First.

You can add the [Key] attribute to the column.

public class Product
{
    [Key]
    public int TestID { get; set; }
}

Entity Framework Code First uses convention over configuration and by default will look for a column named "ID" to make it the primary key. Otherwise you have to it declaratively.

Upvotes: 5

KallDrexx
KallDrexx

Reputation: 27813

You have to do one of two things

1) Use DataAnnotations, and in your model class give your idClient property the [Key] attribute. That will tell EF that idClient is your primary key.

2) In your data context's class, you can override the OnModelCreating(ModelBuilder modelBuilder) method. In that method you have to call something like modelBuilder.Entity<MyEntity>().HasKey(x => x.idClient); so EF knows that this is an identity and key column.

By default, EF4 Code First only automatically sets a column as a primary key if it is named Id or <entity name>Id.

Upvotes: 2

Related Questions