如何使用 EF 和 linq 获取带有嵌套信息的实体
How can I get this entity with nested information using EF and linq
我有 3 个相关的表。员工、亲戚、RelationTypeCatalog。关系是IX_Relatives_EmployeeId和IX_Relatives_RelationTypeCatalogId。
如何使用 EF 编写此查询?
我正在尝试从一名员工那里获取信息,该员工的亲属名单以及他们之间的关系类型。到目前为止,我已经尝试了这些选项:
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"
]
}
尝试使用 Include 和 Then Include,如下所示:
return await _context.Employees
.Include(emp=> emp.Relatives).ThenInclude(rel => rel.RelationTypeCatalog)
.FirstOrDefaultAsync(emp=>emp.Id == id);
我有 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"
]
}
尝试使用 Include 和 Then Include,如下所示:
return await _context.Employees
.Include(emp=> emp.Relatives).ThenInclude(rel => rel.RelationTypeCatalog)
.FirstOrDefaultAsync(emp=>emp.Id == id);