Thisen
Thisen

Reputation: 183

One-To-Many and One-To-Many relationship in Entity Framework 6

Now I have been trying for too long to make this work.

I have three entities:

public class Item
{
    public int ItemId { get; set; }
    public string ItemName { get; set; }
    public int StdVolume { get; set; }
    public string StdUnit { get; set; }

    public ICollection<ListItem> ListItems { get; set; } 
}

public class ListItem
{
    public int Amount { get; set; }
    public int Volume { get; set; }
    public string Unit { get; set; }

    public List List { get; set; }
    public Item Item { get; set; }
}

public class List
{
    public int ListId { get; set; }
    public string ListName { get; set; }

    public ICollection<ListItem> ListItems { get; set; } 
}

As you can see I have One-To-Many between Item and ListItem, and One-To-Many between Item and ListItem.

I feel like I have tried everything in:

protected override void OnModelCreating(DbModelBuilder modelBuilder)

HasKey, Required, everything. I just don't know how to "map" it around.

Can anyone help?

EDIT: I want ListItem to be a weak entity, therefore its PK's and FK's should be ListId and ItemId.

Upvotes: 0

Views: 90

Answers (1)

ocuenca
ocuenca

Reputation: 39376

This is actually a many-to-many relationship and you are trying to map explicitly the junction table, so, in the ListItem class you need to add these two Ids properties:

 public class ListItem
 {
    public int  ListId { get; set; }

    public int ItemId { get; set; }
    //...
 }

And the configuration of both relationships would be this way:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<ListItem>().HasKey(li => new {li.ListId, li.ItemId});

        modelBuilder.Entity<ListItem>()
            .HasRequired(li => li.List)
            .WithMany(l => l.ListItems)
            .HasForeignKey(li => li.ListId);

        modelBuilder.Entity<ListItem>()
            .HasRequired(li => li.Item)
            .WithMany(l => l.ListItems)
            .HasForeignKey(li => li.ItemId);
}

Upvotes: 1

Related Questions