c# - 使用 Entity Framework 返回所有相关实体

标签 c# entity-framework

我是第一次使用 Entity Framework。我正在编写以下简单查询:

public List<Request> GetResult(string code)
{
    List<Request> requests = new List<Request>();

    using (var db = new Context())
    {
        requests = (from c in db.Requests where c.Code == code select c).ToList();
    }

    return requests;
}

Request 对象有一些相关实体,例如 Results 表与 Request 具有一对一关系> 表。然而,他们都回来了。

如何使用 Entity Framework 进行查询并返回实体及其所有相关实体?

TIA

最佳答案

使用预先加载的单个查询

db.Requests.Where(req => req.Code == code)
    .Include(req => req.Results) // Joining is performed here
    .Include(req => req.SomeOtherProperty)
    .ToList()

使用显式加载的多个查询

// Hits the database once.
var requests = db.Requests.Where(req => req.Code == code).ToList();
var requestIDs = requests.Select(req => req.ID);
// Hits the database another time to load your Results property.
db.Results.Where(res => requestIDs.Contains(res.RequestID)).Load(); 

如果启用延迟加载,每次访问 Request 列表的 Results 属性时,都会对数据库执行查询以加载它,这可能会导致在 N+1 问题中。不过,延迟加载在 EntityFramework Core 上尚不可用。

关于c# - 使用 Entity Framework 返回所有相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44318571/

相关文章:

c# - Raspberry PI - I2C 不写入数据

entity-framework - CQRS与 Entity Framework 自跟踪实体/WCF RIA服务兼容吗?

c# - 用于服务/使用 OData 接口(interface)的 Entity Framework 的替代方案

c# - 一种漂亮地打印 C# 对象的方法

c# - Linq 查询具有 where 条件的表中的不同数据

c# - 如何将 Nullable 运算符与 Null 条件运算符一起使用?

c# - Entity Framework 、依赖注入(inject)和共享对象

c# - 在 Entity Framework 中添加/删除多对多关联

c# - 将 GroupBy DateTime 与 Entity Framework 一起使用会引发异常

c# - Azure 存储表和数据迁移