【问题标题】:Select data using a Linq expression as sub expresion inside another Linq expression [duplicate]使用 Linq 表达式选择数据作为另一个 Linq 表达式中的子表达式 [重复]
【发布时间】:2021-07-01 14:23:40
【问题描述】:

我们使用带有动态 Linq 表达式的实体框架从数据库中选择数据,其中定义了以下实体:

public class Entity1
{
  int Id { get; set; }
  string Somedata1 { get; set; }
}

public class Entity2
{
  int Id { get; set; }
  string Somedata2 { get; set; }
  IList<EntityLink> LinkedEntities1 { get; set; }
}

public class EntityLink
{
  int Id { get; set; }
  Entity1 ent1 { get; set; }
  Entity2 ent2 { get; set; }
}

实体Entity1Entity2 具有n-n 关系。

我们使用Entity1动态选择数据形式(其中selectExpression定义为Expression&lt;Func&lt;Entity1, object&gt;&gt;

var selectExpression = await modelEntity1.GetSelectExpression(); // model for `Entity1`

return await dbcontext.Entity1
  .AsQueryable()
  .Where(g => ...)
  .Select(selectExpression)
  .ToListAsync();

但在另一个例程中,我想在枚举Entity2 的“链接”记录时使用相同的selectExpressionEntity1 中选择数据:

var selectExpression = await modelEntity1.GetSelectExpression();

return await dbcontext.Entity2
  .AsQueryable()
  .Where(e2 => ...)
  .Select(e2 => new {
    Id = e2.Id,
    // etc.
    ChildData = e2.LinkedEntities1.Select(l => new {
      LinkId = l.Id,
      LinkData = l.ent1.Select(selectExpression), // <- Does not compile as no 'Select' method exists
    }),
  })
  .ToListAsync();

【问题讨论】:

  • 确切的编译器错误是什么? (“这不可能”信息量不大)。
  • @OlivierJacot-Descombes 是的,你的权利 - 我已经更新了注释以说明无法编译,因为 Select 方法不存在 - 所以我正在寻找可用的东西/可以使用。
  • ent1 不是IQueryable 类型,而是Entity1 类型,它没有Select {extension} 方法。将l.ent1.Select(selectExpression) 替换为selectExpression(l.ent1)
  • @Orace 这甚至无法编译。
  • @Servy 你是对的。这就是使这个问题变得有趣的原因:如何将选择表达式应用于表达式中的单个对象。

标签: c# entity-framework linq-expressions


【解决方案1】:

尝试更改您的查询以实际包含子实体:

dbcontext.Entity2.Include(x=>x.LinkedEntities1)

【讨论】:

  • 因为我不想只包含有关LinkedEntities1 的所有数据,而只想包含使用selectExpression 返回的特定成员,所以这不是一个选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
相关资源
最近更新 更多