【问题标题】:How can I get this entity with nested information using EF and linq如何使用 EF 和 linq 获取具有嵌套信息的实体
【发布时间】:2019-10-21 03:09:10
【问题描述】:

我有 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"
    ]
}

【问题讨论】:

    标签: c# entity-framework .net-core entity-framework-6 linq-to-entities


    【解决方案1】:

    尝试使用 Include 和 Then Include,如下所示:

    return await _context.Employees
                .Include(emp=> emp.Relatives).ThenInclude(rel => rel.RelationTypeCatalog)
                .FirstOrDefaultAsync(emp=>emp.Id == id);
    

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2011-11-02
      • 2014-03-17
      相关资源
      最近更新 更多