6

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nugs
  • 5,503
  • 7
  • 36
  • 57
  • What version of Entity Framework are you using? And can you post your `Request` object? – Steve Jun 01 '17 at 23:33
  • https://stackoverflow.com/questions/14512285/entity-framework-is-there-a-way-to-automatically-eager-load-child-entities-wit – spender Jun 01 '17 at 23:51

2 Answers2

10

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.

IvanJazz
  • 763
  • 1
  • 7
  • 19
  • 1
    After adding the System.Data.Entity namespace your eager loading example did the trick nicely. Thx! – Nugs Jun 02 '17 at 14:33
  • 1
    lazy loading is now avail as of EF Core 2.1 https://learn.microsoft.com/en-us/ef/core/querying/related-data – Dylan Hayes Jun 28 '18 at 05:24
0

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

this.Configuration.LazyLoadingEnabled = true; 
shop350
  • 198
  • 1
  • 6