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?
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
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