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方法实现的
using (var context = new BloggingContext())
{
// Load all blogs and related posts
var blogs1 = context.Blogs
.Include(b => b.Posts)
.ToList(); // Load one blogs and its related posts
var blog1 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include(b => b.Posts)
.FirstOrDefault(); // Load all blogs and related posts
// using a string to specify the relationship
var blogs2 = context.Blogs
.Include("Posts")
.ToList(); // Load one blog and its related posts
// using a string to specify the relationship
var blog2 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include("Posts")
.FirstOrDefault();
}
延迟加载通过virtual关键字进行实现(当EF框架禁用了延迟加载,这种方式就无效了)
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Tags { get; set; } public virtual ICollection<Post> Posts { get; set; }
} //禁用延迟加载
public class BloggingContext : DbContext
{
public BloggingContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}
当禁用了延迟加载后或不使用延迟加载时,通过显示加载仍然可以获取管理的数据
using (var context = new BloggingContext())
{
var post = context.Posts.Find(); // 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(); //一对多时使用Collection
// 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();
} //使用Query方式进行一些过滤
using (var context = new BloggingContext())
{
var blog = context.Blogs.Find(); // Load the posts with the 'entity-framework' tag related to a given blog
context.Entry(blog)
.Collection(b => b.Posts)
.Query()
.Where(p => p.Tags.Contains("entity-framework")
.Load(); // Load the posts with the 'entity-framework' tag related to a given blog
// using a string to specify the relationship
context.Entry(blog)
.Collection("Posts")
.Query()
.Where(p => p.Tags.Contains("entity-framework")
.Load();
}