【问题标题】:Linq Dynamic query and include non related entityLinq 动态查询并包含非相关实体
【发布时间】:2017-04-09 12:45:34
【问题描述】:

我有一个场景,我有 3 个实体

class entityA
{
    public Guid Id { get; set; }
    public string NameA { get; set; }
}


class entityB
{
    public Guid Id { get; set; }
    public string NameB { get; set; }
    public entityA EntityA { get; set; }
}

class entityC
{
    public Guid Id { get; set; }
    public Guid HistoryId { get; set; }
}

EntityA 和 entityB 有关系,但 entityC 没有任何关系。

我可以获取 entityA 和相关 entityB 的数据

db.entityA.Include(x=>x.entityB)

但我不能对 entityA 和 entityC 执行 include(),因为 entityA 和 entityC 之间没有关系。

只有使用 Linq Query 语法才能实现,如下所示:

from A in entityA join C in entityC on A.Id equals C.HistoryId select A

有什么方法可以使用 Linq Lambda 语法包含()或连接 entityA 和 entityC 吗?

【问题讨论】:

标签: c# entity-framework linq dynamic-linq linq-expressions


【解决方案1】:

根据您的查询,A 和 C 之间存在逻辑关系。 您可以将ForeignKey 属性放在C 类实体映射中,然后您可以在查询中使用Include。

class entityC
{
  public Guid Id { get; set; }

  public Guid HistoryId { get; set; }

  [ForeignKey("HistoryId")]
  public entityA EntityA { get; set; }
}

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    相关资源
    最近更新 更多