Linq 包括和 Where 关于父子关系的条件



这是我的场景:

我有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,该员工是否受雇?员工具有字符串的唯一用户 ID。我在 api 调用中通过 endpoit 传递该字符串

编辑

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; }
}

由于您实际上是按配置文件 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

它应该有效。

我认为您需要包括内部检查,以确定给定userId Company中是否有Any员工:

//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);
}

最新更新