C# Entity-Framework: How can I combine a .Find and .Include on a Model Object?

前端 未结 5 981
感情败类
感情败类 2020-11-27 11:36

I\'m doing the mvcmusicstore practice tutorial. I noticed something when creating the scaffold for the album manager (add delete edit).

I want to write code elegantl

5条回答
  •  醉酒成梦
    2020-11-27 12:26

    Dennis' answer is using Include and SingleOrDefault. The latter goes round-tripping to database.

    An alternative, is to use Find, in combination with Load, for explicit loading of related entities...

    Below an 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(); 
    }
    

    Of course, Find returns immediately without making a request to the store, if that entity is already loaded by the context.

提交回复
热议问题