How to include related tables in DbSet.Find()?

c# entity-framework-core


If I want to include related objects in an EF7 query, it's nice and easy:

var myThing = db.MyThings
                .Include(t => t.RelatedThing)
                .Where(t => t.SomeCondition == true)

Also, there's a nice method on the DbSet<T> that makes it easy to load a single object by its key:

var myThing = db.MyThings.Find(thingId);

But now I want to load myThing by its Id, along with its RelatedThing. Unfortunately (and understandably) .Find() is a method of DbSet<T>, not IQueryable<T>. Obviously I could do this:

var myThing = db.MyThings
                .Include(t => t.RelatedThing)
                .SingleOrDefault(t => t.MyThingId == thingId);

But I specifically want to use the .Find() method, because it's nice and generic and I'm writing a method that generically loads a record along with "included" relationships specified by an Expression<Func<T, object>>.

Any suggestions how to do this?

9/11/2016 9:53:26 AM

Accepted Answer

It was not possible with EF6, I don't think EF Core will change that. This is because the main purpose of the Find method is to bring the already loaded entity from the local cache, or load it from the database if it's not there. So the eager loading (Include) can be used only in the later case, while in the former it would need to perform explicit loading. Combining both in a single method might be technically possible, but is hard.

I think you should take the FirstOrDefault (or SingleOrDefault) route combined with eager loading. You can see a sample implementation for EF6 in Repository generic method GetById using eager loading. It could be adjusted for EF Core like using the dbContext.Model.FindEntityType(typeof(T)).FindPrimaryKey().Properties to find the PK properties and build the predicate. Also since EF Core includes are bit more complicated (require Include / ThenInclude chains), you might find interesting this thread Can a String based Include alternative be created in Entity Framework Core?.

5/23/2017 12:16:22 PM

Popular Answer

Use Find, in combination with Load, for explicit loading of related entities. Below a MSDN example:

using (var context = new BloggingContext()) 
  var post = context.Posts.Find(2); 

  // Load the blog related to a given post 
  context.Entry(post).Reference(p => p.Blog).Load(); 

  // Load the blog related to a given post using a string  

  var blog = context.Blogs.Find(1); 

  // Load the posts related to a given blog 
  context.Entry(blog).Collection(p => p.Posts).Load(); 

  // Load the posts related to a given blog  
  // using a string to specify the relationship 

here is MSDN link

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow