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

后端 未结 2 1903
梦毁少年i
梦毁少年i 2021-01-13 20:06

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

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


        
相关标签:
2条回答
  • 2021-01-13 20:33

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

    0 讨论(0)
  • 2021-01-13 20:40

    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

    0 讨论(0)
提交回复
热议问题