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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With