EF中加载实体的方式
生活随笔
收集整理的這篇文章主要介紹了
EF中加载实体的方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?EF中的查詢執行時機:
1.?foreach進行枚舉
2.?ToArray、ToList、ToDictionary
3.?Linq的一些操作,如First、Any
4.?DbSet上的Load操作。DbEntityEntry.Reload和Database.ExecuteSqlCommand
在web application中,每一個請求使用一個context實例;在WPF中,每個form使用一個context實例
context不是線程安全的
加載實體的方式:
1.貪婪加載(eager loading)
2.延遲加載(lazy loading)
3.顯示加載(explicit loading)
?
貪婪加載實現是通過include方法實現的
1 using (var context = new BloggingContext()) 2 { 3 // Load all blogs and related posts 4 var blogs1 = context.Blogs 5 .Include(b => b.Posts) 6 .ToList(); 7 8 // Load one blogs and its related posts 9 var blog1 = context.Blogs 10 .Where(b => b.Name == "ADO.NET Blog") 11 .Include(b => b.Posts) 12 .FirstOrDefault(); 13 14 // Load all blogs and related posts 15 // using a string to specify the relationship 16 var blogs2 = context.Blogs 17 .Include("Posts") 18 .ToList(); 19 20 // Load one blog and its related posts 21 // using a string to specify the relationship 22 var blog2 = context.Blogs 23 .Where(b => b.Name == "ADO.NET Blog") 24 .Include("Posts") 25 .FirstOrDefault(); 26 } View Code延遲加載通過virtual關鍵字進行實現(當EF框架禁用了延遲加載,這種方式就無效了)
1 public class Blog 2 { 3 public int BlogId { get; set; } 4 public string Name { get; set; } 5 public string Url { get; set; } 6 public string Tags { get; set; } 7 8 public virtual ICollection<Post> Posts { get; set; } 9 } 10 11 //禁用延遲加載 12 public class BloggingContext : DbContext 13 { 14 public BloggingContext() 15 { 16 this.Configuration.LazyLoadingEnabled = false; 17 } 18 } View Code當禁用了延遲加載后或不使用延遲加載時,通過顯示加載仍然可以獲取管理的數據
1 using (var context = new BloggingContext()) 2 { 3 var post = context.Posts.Find(2); 4 5 // Load the blog related to a given post 6 context.Entry(post).Reference(p => p.Blog).Load(); 7 8 // Load the blog related to a given post using a string 9 context.Entry(post).Reference("Blog").Load(); 10 11 var blog = context.Blogs.Find(1); 12 13 //一對多時使用Collection 14 // Load the posts related to a given blog 15 context.Entry(blog).Collection(p => p.Posts).Load(); 16 17 // Load the posts related to a given blog 18 // using a string to specify the relationship 19 context.Entry(blog).Collection("Posts").Load(); 20 } 21 22 //使用Query方式進行一些過濾 23 using (var context = new BloggingContext()) 24 { 25 var blog = context.Blogs.Find(1); 26 27 // Load the posts with the 'entity-framework' tag related to a given blog 28 context.Entry(blog) 29 .Collection(b => b.Posts) 30 .Query() 31 .Where(p => p.Tags.Contains("entity-framework") 32 .Load(); 33 34 // Load the posts with the 'entity-framework' tag related to a given blog 35 // using a string to specify the relationship 36 context.Entry(blog) 37 .Collection("Posts") 38 .Query() 39 .Where(p => p.Tags.Contains("entity-framework") 40 .Load(); 41 } View Code?
轉載于:https://www.cnblogs.com/goodlucklzq/p/4665899.html
總結
以上是生活随笔為你收集整理的EF中加载实体的方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Notepad++加上xml格式化的功能
- 下一篇: java的本地文件操作