开发者

Defining Primary Key for entity CodeFirst Ef4

开发者 https://www.devze.com 2023-03-15 15:40 出处:网络
I want to define a primar开发者_开发技巧y 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 want to define a primar开发者_开发技巧y 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?


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);
}


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);
     }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消