简体   繁体   English

实体框架6中的一对多和一对多关系

[英]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. 如您所见,我在Item和ListItem之间有一对多,在Item和ListItem之间有一对多。

I feel like I have tried everything in: 我觉得我已经尝试了所有方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)

HasKey, Required, everything. HasKey,必填,所有内容。 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. 编辑:我希望ListItem是一个弱实体,因此它的PK和FK应该是ListId和ItemId。

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: 这实际上是一个多对多关系,并且您试图显式映射联结表 ,因此,在ListItem类中,您需要添加以下两个Ids属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM