user3564870 user3564870 - 12 days ago 4
C# Question

Code First Entity Framework Lazy Loading Not Working

I'm having trouble getting lazy loading to work.

If I do this:

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());

}
}
}


"Post count" is ALWAYS 0;

BUT if I uncomment the Load() calls before the foreach, the Post count is correct. Any ideas what's wrong?

Here's the entity classes being used:

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; }
}

Answer

Turns out the issue was using a local MS SQL database. Using SQLite doesn't have the issues.

Comments