【问题标题】:Linq Include and Where conditions on Parent-child relationLinq Include 和 Where 的父子关系条件
【发布时间】:2019-05-30 23:47:49
【问题描述】:

这是我的场景:

我有Company的模型:

public class Company
{
    [Key]
    public int Id      { get; set; }
    public string Name { get; set; }

    public virtual List<Product>  Products  { get; set; }
    public virtual List<Employee> Employees { get; set; }
}

以及如下所示的 API 端点:

    //GET: api/company/Profile?id=stringid
    [Route("Profile")]
    [ResponseType(typeof(Company))]
    public IHttpActionResult<Company> GetEmployeeCompany(string userId)
    {
         var company = db.Companies
                 .Include(p => p.Products)
                 .Where(u => u.Employees.userId == userId);

         return Ok(company)

        //that return dont work ofc, but i just want to show what im talking about
    }

我的问题是,如何使用他的产品找到Company,该员工是受雇的?员工具有唯一的 userId,即字符串。我在 api 调用中通过端点传递该字符串

编辑

Employee

public class Employee
{
    [Key]
    [ForeignKey("User"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string UserId { get; set; }
    public int CompanyId { get; set; }

    public virtual Company         Company { get; set; }
    public virtual ApplicationUser User    { get; set; }
}

【问题讨论】:

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


    【解决方案1】:

    由于您实际上是按个人资料 ID 进行搜索,因此您可能希望按个人资料 ID 加载员工并包括其公司和公司的产品:

    var employee = db.Employees
        .Include(e => e.Company.Products)
        .SingleOrDefault(e => e.Id == userId);
    
    return employee.Company.Products; // to return company's products
    return employee.Company; // to return company, will contain all products
    

    它应该工作。

    【讨论】:

    • 我收到一个错误,Company 不包含 Select 的定义
    • 是否有可能在返回时获得Company 属性而不是Employee
    • @michasaucer 哦,当然,抱歉,请您查看更新后的答案。我希望它有所帮助。
    • 我对我的帖子进行了编辑,我更改了返回类型,抱歉出现问题
    • @michasaucer 我不知道你说的第二个问题是什么意思,但是在db.Employees 中搜索它是很自然的,因为你实际上是通过员工的ID而不是公司的ID来搜索的。
    【解决方案2】:

    我认为您需要对Company 中是否有Any 员工与给定的userId 进行内部检查:

    //GET: api/company/Profile?id=stringid
    [Route("Profile")]
    [ResponseType(typeof(Company))]
    public IHttpActionResult<Company> GetEmployeeCompany(string userId)
    {
        var company = db.Companies
                 .Include(p => p.Products)
                 .FirstOrDefault(u => u.Employees.Any(e => e.UserId == userId));
    
         if (company == null)
         {
             return NotFound();
         }
    
         return Ok(company);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多