In EF4 Code first Collection are not lazy loading?
Using Microsoft Visual C# 2010 Express, Entity Framework Feature CTP4.
I tried EF4 with code first with something small based on Scott Gu's blog. But it seems that collections are not initialized when retrieving an entity. I get a null reference exception when adding a product to a category. In all the examples I've seen, the collection are never explicitly initialized. What am I missing?
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var _db = new Northwind();
var c = new Category { CategoryName = "Testcat" };
_db.Categories.Add(c);
_db.SaveChanges();
var c2 = _db.Categories.SingleOrDefault(i => i.CategoryId==c.CategoryId);
var pr = new Product { ProductName = "testprod" };
c2.Products.Add(pr); // <--- Null reference for Products
_db.SaveChanges();
Console.WriteLine("Done...");
Console.ReadKey();
}
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public virtual Category Category { get; set; }
}
public class Category
开发者_运维技巧 {
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Northwind : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
}
Lazy loading doesn't work for POCOs. You need a proxy. You can get this by replacing
var c = new Category { CategoryName = "Testcat" };
with
var c = _db.Categories.Create();
c.CategoryName = "Testcat";
Your other option is still use a POCO without a proxy and create this list yourself and replace
c2.Products.Add(pr);
with
c2.Products = new List<Product> { pr };
as the comment by Yury Tarabanko says, the category that is returned is null since you don't have a category id for c since it hasn't been assigned.
var c2 = _db.Categories.SingleOrDefault(i => i.CategoryName == c.CategoryName);
var pr = new Product { ProductName = "testprod" };
c2.Products.Add(pr);
will work since you assigned c.CategoryName with the value of "Testcat"
精彩评论