简体   繁体   English

实体框架代码优先:一对多循环引用

[英]Entity Framework Code First: One-to-many cyclic reference

I'm using EF 6.1 with code-first and auto migrations enabled. 我正在使用启用代码优先和自动迁移功能的EF 6.1。 So far my model (relevant properties only) looks like this: 到目前为止,我的模型(仅相关属性)如下所示:

public class Inventory : IEntity {
    public virtual ICollection<Room> Rooms { get; set; }
    public virtual ICollection<Item> Items { get; set; }
}

public class Item : IEntity {
    public int RoomId { get; set; }
    public int InventoryId { get; set; }

    [ForeignKey("RoomId")]
    public Room Room { get; set; }

    [ForeignKey("InventoryId")]
    public Inventory Inventory { get; set; }
}

public class Room : IEntity {
    public ICollection<Item> Items { get; set; }
    public int InventoryId { get; set; }

    [ForeignKey("InventoryId")]
    public Inventory Inventory { get; set; }
}

And in my DbContext I create the references by: 在我的DbContext中,通过以下方式创建引用:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Room>()
                .HasRequired<Inventory>(room => room.Inventory)
                .WithMany(inv => inv.Rooms)
                .HasForeignKey(room => room.InventoryId);

    modelBuilder.Entity<Item>()
                .HasRequired<Room>(item => item.Room)
                .WithMany(room => room.Items)
                .HasForeignKey(item => item.RoomId);

    modelBuilder.Entity<Item>()
                .HasRequired<Inventory>(item => item.Inventory)
                .WithMany(inv => inv.Items)
                .HasForeignKey(item => item.InventoryId);
}

In terms of modeling, what I'd expect to have is: 在建模方面,我期望拥有:

  • 1 inventory <-> n rooms 1个库存<-> n个房间
  • 1 room <-> n items 1个房间<-> n个物品
  • 1 inventory <-> n items 1个库存<-> n个项目

Thus I want to be able to filter items either by inventories directly or by rooms. 因此,我希望能够直接按库存或按房间过滤商品。 When running the application and first accessing the DbContext, a SqlCeException is thrown, telling me that there are cyclic references. 当运行应用程序并首次访问DbContext时,将引发SqlCeException,告诉我有循环引用。 Now, since the Inventory is the master entity in all cases and there's just another detail step (rooms) -- which can be skipped for filtering --, I don't see any cycles in my graph. 现在,由于库存在所有情况下都是主实体,并且仅存在另一个详细信息步骤(房间)(可以跳过以进行过滤),因此在图形中看不到任何周期。

Any hints? 有什么提示吗?

could it be a possibility that you have two item entity's item with different requirements. 您可能有两个具有不同要求的项目实体的项目。 mayb that has something to do with it, and are you sure that the error has something to do with your graph and not some where else in your code. mayb与它有关,并且您确定错误与图形有关,而不与代码中的其他地方有关。

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

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