Stacker
Stacker

Reputation: 8237

Defining Primary Key for entity CodeFirst Ef4

I want to define a primary key for a POCO entity but i dont want to decorate the entity with primary key attribute i wanna define that from the context class which extend DbContext

i know i should use something like:

Entity<Order>().HasKey(x => x.OrderId);

but i dont know how to do that in my context class.

any help?

Upvotes: 0

Views: 930

Answers (2)

zoranmax
zoranmax

Reputation: 79

You should create a class that defines your context, and then you have to override the OnModelCreating method. Try this:

public class MyContext: DbContext
{
     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
       modelBuilder.Entity<Order>().HasKey(x => x.OrderId);
       base.OnModelCreating(modelBuilder);
     }
}

Upvotes: -1

Dennis Traub
Dennis Traub

Reputation: 51674

In you DbContext-class you can override OnModelCreating like this

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>.HasKey(x => x.OrderId);
    base.OnModelCreating(modelBuilder);
}

Upvotes: 2

Related Questions