Entity Framework CTP4 and composite keys

和自甴很熟 提交于 2020-01-01 06:38:30

问题


I was playing with EntityFramework CTP4 and decided to apply it to one of my current projects. The application uses a SQLServer database and there is one table with a composite key. Say, table "MyEntity" has "Key1" and "Key2" as both foreign keys (individually) and as a composite primary key.

I made a configuration class derived from EntityConfiguration :

class MyEntityConfiguration : EntityConfiguration<MyEntity>
{
    public MyEntityConfiguration()
    {
        HasKey(m => m.Key1);
        HasKey(m => m.Key2);
    }
}

Then in my DataContext (derived from DbContext) :

    public DbSet<MyEntity> MyEntities { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new MyEntityConfiguration());
    }

The problem is that when I query "MyEntities" for all its records :

var entities = from e in MyModel.Instance.MyEntities
               select e;

I get a really weird result consisting of the first record repeated 18 times, then the second repeated 18 times (for the record, my table has 36 records).

I suspect the problem is with the composite key as no other entity is showing this problem.

Any help would be appreciated, thanks :)


回答1:


I haven't tested it with my current database & CTP4 but in CTP3 you'd create a composite key like this:

HasKey(m => new { m.Key1, m.Key2 });


来源:https://stackoverflow.com/questions/3299268/entity-framework-ctp4-and-composite-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!