How to load an entity:
1. Greedy loading (eager loading)
2. Deferred load (lazy loading)
3. Display loading (explicit loading)
Greedy load implementations are implemented by the Include method
1 using(varContext =NewBloggingcontext ())2 {3 //Load all blogs and related posts4 varBLOGS1 =context. Blogs5. Include (b =b.posts)6 . ToList ();7 8 //Load One blogs and its related posts9 varBlog1 =context. BlogsTen. Where (b = B.name = ="ADO Blog") One. Include (b =b.posts) A . FirstOrDefault (); - - //Load all blogs and related posts the //using a string to specify the relationship - varBLOGS2 =context. Blogs -. Include ("Posts") - . ToList (); + - //Load One blog and its related posts + //using a string to specify the relationship A varBLOG2 =context. Blogs at. Where (b = B.name = ="ADO Blog") -. Include ("Posts") - . FirstOrDefault (); -}View Code
Deferred loading is implemented with the virtual keyword (this is not possible when the EF framework disables lazy loading)
1 Public classBlog2 { 3 Public intBlogId {Get;Set; } 4 Public stringName {Get;Set; } 5 Public stringURL {Get;Set; } 6 Public stringTags {Get;Set; } 7 8 Public VirtualIcollection<post> Posts {Get;Set; } 9 }Ten One //Disable Lazy loading A Public classBloggingcontext:dbcontext - { - PublicBloggingcontext () the { - This. configuration.lazyloadingenabled =false; - } -}View Code
When lazy loading is disabled or when lazy loading is not used, managed data can still be obtained by displaying the load
1 using(varContext =NewBloggingcontext ())2 {3 varPost = context. Posts.find (2);4 5 //Load The blog related to a given post6Context. Entry (POST). Reference (p =p.blog). Load ();7 8 //Load The blog related to a given post using a string9Context. Entry (POST). Reference ("Blog"). Load ();Ten One varBlog = context. Blogs.find (1); A - //A couple of long use collection - //Load The posts related to a given blog theContext. 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 (); - } + A //use the Query method to do some filtering at using(varContext =NewBloggingcontext ()) - { - varBlog = context. Blogs.find (1); - - //Load The posts with the ' entity-framework ' tag related to a given blog - context. Entry (blog) in. Collection (b =b.posts) - . Query () to. Where (p = p.tags.contains ("entity-framework") + . Load (); - the //Load The posts with the ' entity-framework ' tag related to a given blog * //using a string to specify the relationship $ context. Entry (blog)Panax Notoginseng. Collection ("Posts") - . Query () the. Where (p = p.tags.contains ("entity-framework") + . Load (); A}View Code
How entities are loaded in EF