这是我的场景:
我的模型为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,它是字符串。我通过endpoit在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; }
}
答案 0 :(得分:2)
由于您实际上是通过个人资料ID进行搜索的,因此您可能希望通过个人资料ID加载员工并包括其公司及其公司的产品:
@RequestMapping
public String welcome(@SessionAttribute("address") Address address) {
// something....
}
应该可以。
答案 1 :(得分:2)
我认为您需要对给定的Any
内的Company
内是否有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);
}