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

可紊 提交于 2019-12-01 04:40:27

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/39434878/how-to-include-related-tables-in-dbset-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!