【发布时间】:2019-10-21 03:09:10
【问题描述】:
我有 3 个相关的表。员工,相对,RelationTypeCatalog。关系是 IX_Relatives_EmployeeId 和 IX_Relatives_RelationTypeCatalogId。
我正在尝试从某个员工那里获取信息、该员工的亲属名单以及他们之间的关系类型。到目前为止,我已经尝试了这些选项:
public async Task<Employee> GetEmployee(int id)
{
//(1) tried this
return await _context.Employees
.Include(emp=> emp.Relatives.Select(rel=>
rel.RelationTypeCatalog))
.FirstOrDefaultAsync(emp=>emp.Id == id);
}
//(2) also tried this...
public async Task<Employee> GetEmployee(int id)
{
var test = (from e in _context.Employees
join re in _context.Relatives
on e.Id equals re.EmployeeId
join t in _context.RelationTypes
on re.RelationTypeCatalogId equals t.Id
where e.Id == id
select e).FirstOrDefaultAsync();
return await test;
}
这是使用 SQL 查询的样子
SELECT *
from sagrha.employees
inner join sagrha.relatives
on employees.Id = relatives.EmployeeId
inner join sagrha.relationtypes
on relatives.RelationTypeCatalogId= sagrha.relationtypes.Id;
我正在寻找一个看起来像
的 json 结果{
"id": 1,
"name": "Homero",
"gender": "male",
"relatives": [
"Name":"Bart"
"RelationType":"Child"
]
}
【问题讨论】:
标签: c# entity-framework .net-core entity-framework-6 linq-to-entities