Entity Framework CTP4 and composite keys
Asked Answered
C

1

4

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 :)

Convoy answered 21/7, 2010 at 12:39 Comment(3)
CTP4??? Why not use the release version? It's out!Regazzi
My bad, I meant the just released Feature CTP4 which improves the Code-First approach.Convoy
EntityConfiguration looks like it is EntityTypeConfiguration in EF4.1.Gantry
C
6

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 });
Coze answered 21/7, 2010 at 13:3 Comment(3)
As incredible as it may sound it actually worked :o I always assumed those were different ways to do the same thing, guess I was wrong. Thanks :)Convoy
Glad it worked! Yeah it's not entirely clear how to do all things with the lack of documentation currently.Coze
Just had this issue myself and this is the correct way of setting composite keys. Thanks @TheCloudlessSky. NB. using HasKey repeatedly as follows: HasKey(m => m.Key1); HasKey(m => m.Key2); will only remember the last key that was set.Monosyllable

© 2022 - 2024 — McMap. All rights reserved.