【问题标题】:Lambda Expression with Join table带有连接表的 Lambda 表达式
【发布时间】:2016-02-07 17:34:00
【问题描述】:

我有以下实体

  1. 项目
  2. 组件
  3. 项目组件

我想写一个类似的方法

GetProjectsByComponentId(int componentId)
{ /* some code*/}

请帮我写一个 lambda 表达式。

来自 EF 生成的架构的片段:

public partial class ProjectComponent
{
    public int ID { get; set; }
    public Nullable<int> ProjectID { get; set; }
    public Nullable<int> ComponentID { get; set; }
    public string Comment { get; set; }

    public virtual Component Component { get; set; }
    public virtual Project Project { get; set; }
}

public partial class Project
{
    public Project()
    {
        this.ProjectComponents = new HashSet<ProjectComponent>();
    }

    public int ID { get; set; }
    public string Description { get; set; }

    public virtual ICollection<ProjectComponent> ProjectComponents { get; set; }
}

public partial class Component
{
    public Component()
    {
        this.ProjectComponents = new HashSet<ProjectComponent>();
    }

    public int ID { get; set; }
    public string Description { get; set; }

    public virtual ICollection<ProjectComponent> ProjectComponents { get; set; }
}

【问题讨论】:

  • 我想表达这样的查询...返回 ctx.Projects.Where(p => p...。我需要帮助如何完成该表达式
  • 该示例正在寻找具有给定 ProjectId 的项目,这是不同的,另一个示例可能是项目和员工。获取与给定员工关联的所有项目。

标签: c# entity-framework lambda


【解决方案1】:

ComponentID 很遗憾,您提供的信息很少,但我会尽力提供帮助。

假设您有 edmx 或代码优先模型:

ctx.Project.Include(p=>p.ProjectComponents).Where(p => p.ProjectComponents.Any(pc=>pc.ComponentID == id)).ToList();

或 SQL

SELCT p.* FROM Project as p
INNER JOIN ProjectComponent as pc ON pc.ProjectID = p.ID
WHERE pc.ProjectID = @ID

【讨论】:

  • 我已将 EF 生成的架构包含在上面的原始帖子中
  • 我更新了我的 linqu 查询。我认为它应该按预期工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
相关资源
最近更新 更多