插入数据库时​​检测到自引用循环的属性

时间:2019-07-09 18:24:52

标签: c# entity-framework fluent

我正在尝试学习C#Fluent API,而且我的模型设置遇到问题(我认为)。我有三个表:OrderFile,Order,LineItem。错误:

  

为类型为“ BaseService.WebApi.Order”的属性“ order”检测到自引用循环。路径“ orders [0] .lineItems [0]”。

我的结构:

  • OrderFile包含List<Orders>
  • 订单包含List<ListItems>和导航属性OrderFile
  • ListItem包含导航属性Order

它们与Fluent API中指定的ForeignKey约束联系在一起。约束有问题吗?我试图遵循此example for Foreign keys

modelBuilder.Entity<OrderFile>(e =>
            {
                //many orders within one order file
                //the FK relates the OrderFile to the nav key of the Order
                e.HasMany(of => of.Orders)
                .WithOne(o => o.orderFile)
                .HasForeignKey(o => o.FileGuid);

                e.HasKey(o => o.FileGuid);
            });

            modelBuilder.Entity<Order>(e =>
            {
                //each order has an array of line items
                //each line item has one order (navigation property)
                //the foreign key of the line item ties it to the Parent (List<Order>)

                e.HasMany(o => o.LineItems)
                .WithOne(li => li.order)
                .HasForeignKey(o => o.OrderGuid); 

                e.HasKey(o => o.OrderGuid);
            });

模型

public class OrderFile
{
    public Guid FileGuid { get; set; }
    public virtual ICollection<Order> Orders { get; set; } //everything with same FileGuid
}

public class Order
{
    ....
    [JsonIgnore]
    public Guid FileGuid { get; set; }

    [Key]
    public Guid OrderGuid { get; set; }
    [JsonIgnore]
    public OrderFile orderFile { get; set; }
    public virtual ICollection<LineItem> LineItems { get; set; } //everything with same OrderGuid
    }

public class LineItem
{
       ....
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public Guid OrderGuid { get; set; }
        public Order order { get; set; }

}

1 个答案:

答案 0 :(得分:2)

您的LineItem实体具有对Order的引用,该引用没有JsonIgnore属性。

基本上,您的问题源自尝试序列化具有循环依赖关系(循环)的对象图,而设计问题是您在API中使用了数据库实体类。面向客户的模型应该与您在数据库中保留的实体不同的类。