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

后端 未结 2 1923
梦毁少年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: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

提交回复
热议问题