【问题标题】:How to query 3 entities that have references between them with an Entity Framework query如何使用实体框架查询查询它们之间有引用的 3 个实体
【发布时间】:2021-04-10 15:22:09
【问题描述】:

我有 3 个实体,其中 A 和 B 之间有一个引用,B 和 C 之间有另一个引用。

如何查询从实体A开始的数据,其中结果包含来自实体B的相关数据,同样来自实体B的结果包含来自实体C的相关数据。

我能够使用以下命令检索 A 和 B 之间的数据:

context.A.Include(m => m.B).SingleOrDefaultAsync(m => m.b_aid == aid);

结果如下:

{
    aid:1,
    B:[
       { bid:2, b_aid:1},
       { bid:3, b_aid:1}
      ]
}

我希望结果类似于:

{
    aid:1,
    B:[
       {
        bid:2, 
        b_aid:1,
        C: [
            {
              cid:1,
              c_bid:1
            }// end job1 of list C
          ]
       },// end obj1 of list B
       {
        bid:3, 
        b_aid:1,
        C: []
       } // end obj2 of list B
      ] // end B List
}

类的设计如下:

class A 
{
    int aid;
    List<B> b;
}

class B
{
    int bid;
    List<C> c;

    [reference]
    int b_aid;
}

class C
{
    int cid;

    [reference]
    Int c_bid;
}

【问题讨论】:

    标签: c# .net entity-framework linq entity-framework-core


    【解决方案1】:
    context.A
        .Include(a => a.b)
        .ThenInclude(b => b.c)
        .SingleOrDefaultAsync(m => m.b_aid == aid);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多