[英]Code First Entity Framework Lazy Loading Not Working
我在懶惰加載工作時遇到了麻煩。
如果我這樣做:
static void Main(string[] args)
{
using(var db = new BlogContext())
{
//db.Blogs.Load();
//db.Posts.Load();
foreach (var v in db.Blogs)
{
Console.WriteLine("Blog: "+ v.Name+" Post count:"+v.Posts.Count());
}
}
}
“發布計數”總是0;
但是,如果我在foreach之前取消注釋Load()調用,則Post計數是正確的。 有什么想法有什么不對嗎?
這是使用的實體類:
public class Blog
{
public Blog(){
Posts = new List<Post>();
}
[Key]
public int BlogId { get; set; }
public string Name { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
[Key]
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
[ForeignKey("BlogId")]
public virtual Blog Blog { get; set; }
}
public class BlogContext : DbContext
{
public BlogContext()
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
原來問題是使用本地MS SQL數據庫。 使用SQLite沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.