简体   繁体   English

使用实体框架返回所有相关实体

[英]Return all related entities with Entity Framework

I'm playing with Entity Framework for the first time. 我是第一次玩实体框架。 I'm writing the following simply query: 我正在编写以下简单查询:

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;
}

There are a few related entities to the Request object such as a Results table that has a 1-to-1 relation with the Request table. Request对象有一些相关实体,例如与Request表具有Request关系的Results表。 However they are all coming back null. 但是它们都返回null。

How can I query with Entity Framework and return a entity and ALL its related entities? 如何使用Entity Framework查询并返回一个实体及其所有相关实体?

TIA TIA

Single query using eager loading 使用预先加载的单个查询

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

Multiple queries using explicit loading 使用显式加载的多个查询

// 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(); 

If lazy loading is enabled, everytime you access the Results property of Request list, a query is executed to on the database to load it for you, which could result in the N+1 problem. 如果启用了延迟加载,则每次访问“ Request列表的“ Results属性时,都会对数据库执行查询以为您加载它,这可能会导致N + 1问题。 Lazy loading is not yet available on EntityFramework Core though. 延迟加载在EntityFramework Core上尚不可用。

If you want to choose objects to be loaded use 如果要选择要加载的对象,请使用

db.Entry(Requests).Reference(p => p.Code).Load(); 

If you want to load all automatically on your datacontext constructor set 如果要在datacontext构造函数集上自动全部加载

this.Configuration.LazyLoadingEnabled = true; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM