Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. However they are all coming back null.

How can I query with Entity Framework and return a entity and ALL its related entities?

TIA

like image 458
Nugs Avatar asked Feb 05 '23 08:02

Nugs


1 Answers

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. Lazy loading is not yet available on EntityFramework Core though.

like image 97
IvanJazz Avatar answered Feb 12 '23 12:02

IvanJazz