Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
                .ToList();

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?

like image 206
Shaul Behr Avatar asked Sep 11 '16 09:09

Shaul Behr


1 Answers

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  
  context.Entry(post).Reference("Blog").Load(); 

  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 
  context.Entry(blog).Collection("Posts").Load(); 
}

here is MSDN link

like image 174
asfandahmed1 Avatar answered Oct 12 '22 17:10

asfandahmed1