Alex
Alex

Reputation: 155

"Where" clause in Entity Framework not retrieving child entities

Here's the deal.

I have two tables related in my model. We'll name'em: reports and subReports.

It's is very important to mention that I don't know, at this point, the reportId of the report I need, so I need to find it using some parameters. Ok, so, if I need to query one element of reports via EntityFramework, I do the following:

reports myReport = context.reports.Where(r=> r.startYear.Equals(2014) && r.endYear.Equals(2015) && r.reportCategoryId.Equals(1)).SingleOrDefault();

This line retrieves the only report that matches the info.

But here's the problem. If I want to access the collection of subReports that myReport should have, it turns out that such collection is empty. This is my problem, I don't know why. My tables are correctly related.

The weird this is, if I change my query like this:

reports myReport = context.reports.Where(r=> r.reportId.Equals(1)).SingleOrDefault();

The related entities are loaded and the collection has the subreports it should have. See the difference? I had to pass the reportId, but this is not what I need, because, as I already told you, I don't know the reportId.

Do you know what's happening?

Thank you in advance :)

Upvotes: 0

Views: 307

Answers (1)

Martin
Martin

Reputation: 5623

Have you tried any of these techniques?

This is from this MSDN page about eager loading

using (var context = new BloggingContext()) 
{ 
    // Load all blogs and related posts 
    var blogs1 = context.Blogs 
                          .Include(b => b.Posts) 
                          .ToList(); 

    // Load one blogs and its related posts 
    var blog1 = context.Blogs 
                        .Where(b => b.Name == "ADO.NET Blog") 
                        .Include(b => b.Posts) 
                        .FirstOrDefault(); 

    // Load all blogs and related posts  
    // using a string to specify the relationship 
    var blogs2 = context.Blogs 
                          .Include("Posts") 
                          .ToList(); 

    // Load one blog and its related posts  
    // using a string to specify the relationship 
    var blog2 = context.Blogs 
                        .Where(b => b.Name == "ADO.NET Blog") 
                        .Include("Posts") 
                        .FirstOrDefault(); 
}


Some remarks on lazy and eager loading

Generelly I tend to work without lazy loading. I like to know when my entities are loaded and when not (eager loading).

Lazy loading can be turned off

  • completely by setting the respective property on the DbContext:

    this.Configuration.LazyLoadingEnabled = false;

  • for a specific entity when the navigation property is not marked virtual. For more info, see the linked MSDN article

Upvotes: 1

Related Questions