user250773
user250773

Reputation: 579

EF Code First composite key mapping

I'm using the CTP 5 of EF 4 and Code first. I don't get a many-many relation working with a composite key on one side.

    modelBuilder.Entity<Item>()                 
           .HasMany(i => i.Categories)  
           .WithMany(o => o.Items)  
           .Map(
           mc =>
           {                  
               mc.ToTable("ItemCategories");  
               mc.MapLeftKey(i => i.Id, "ItemId");  
               mc.MapRightKey(o => o.TemplateID, "TemplateId");  
               mc.MapRightKey(o => o.ItemId, "ItemId");                  
           }
           );

So instead of having a simple key for Categories in my matching table, I've got a composite one. And one part of the composite key is also the key for the Item type, which seems to be the problem here.

I get the error: "Each property name in a type must be unique. Property name 'ItemId' was already defined."

How can I configure EF to use a composite key in this case?

Upvotes: 2

Views: 4850

Answers (2)

user250773
user250773

Reputation: 579

public class Category
{            
    [Key]        
    public string ItemId { get; set; }
    [Key]
    public string TemplateId { get; set; }

    public string Value { get; set; }

    public ICollection<Item> Items { get; set; }
}

public class Item
{       
    public string Id { get; set; }       
    public string Name { get; set; }      

    public ICollection<Category> Categories { get; set; }
}

The mapping table ItemCategories is not a POCO, but used for mapping those 2 as shown. It has SQL columns Id (own primary key) ItemId (FK to Item table and Category table) TemplateId (FK to Category table)

and another ID column which maps to a different table.

In my opinion the only difference here to "normal" many-many scenario is the composite key in the ItemCategories table, which builds the relation to the Category table.

Upvotes: 0

Morteza Manavi
Morteza Manavi

Reputation: 33216

Of course you cannot have 2 columns with the same name within one table. This will work:

modelBuilder.Entity<Item>()
            .HasMany(i => i.Categories)
            .WithMany(c => c.Items)
            .Map(m =>
            {
                m.MapRightKey(i => i.Id, "ItemId");
                m.MapLeftKey(c => c.ItemId, "ItemId2");
                m.MapLeftKey(c => c.TemplateId, "TemplateId");
            });

Upvotes: 2

Related Questions