【问题标题】:EF serializes entity to json with included related entities creates a loopEF 将实体序列化为包含相关实体的 json 创建一个循环
【发布时间】:2019-10-11 00:52:18
【问题描述】:

我在我的 WebApi 项目中使用 EF。我有一个数据库,其中包含许多相互关联的表。当我序列化来自表的对象时,它会创建一个奇怪的 json。

我的 EF 查询如下所示。

db.Products.Include(x => x.ProductCategoryRelations)
.Include(x => x.ProductCategoryRelations.Select(c => c.Category))
.Include(x => x.ProductFileRelations)
.Include(x => x.ProductFileRelations.Select(c => c.File))
.Include(x => x.ProductPropertyRelations)
.Include(x => x.ProductPropertyRelations.Select(c => c.Property))
.Include(x => x.ProductColorRelations)
.Include(x => x.ProductColorRelations.Select(c => c.Color))
.Include(x => x.Brand)
.Where(predicate)
.ToListAsync();

因为这个 EF 查询。它会创建一个如下所示的 json,这是不可接受的......

1.Product
    2.Brand
        3.Product
            4.ProductCategoryRelations
                5.Product
                    .....
                    .....
                    .....
                    .....

我该如何解决这个问题?我想拥有一系列产品,但我不是我需要改变才能获得这样的结果。任何帮助将不胜感激。

提前致谢

【问题讨论】:

    标签: c# json entity-framework asp.net-web-api serialization


    【解决方案1】:

    试试这个方法:

    db.Products
    .Where(predicate)
    .Select(p=> new { p.Brand, p.ProductColor.Color_Name, p.ProductCategory.Category_Name })
    .ToListAsync();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2016-02-01
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多