在EF4代码第一集合不是懒惰加载? [英] In EF4 Code first Collection are not lazy loading?
问题描述
使用Microsoft Visual C#2010 Express,实体框架功能CTP4。
Using Microsoft Visual C# 2010 Express, Entity Framework Feature CTP4.
我尝试使用基于,rel =nofollow noreferrer。但是,在检索实体时,似乎没有初始化集合。将产品添加到类别时,我得到一个空引用异常。在我看到的所有示例中,集合从未被显式初始化。我缺少什么?
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?
这是我的代码:
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; }
}
}
推荐答案
懒惰加载不适用于POCO。你需要一个代理您可以通过替换
Lazy loading doesn't work for POCOs. You need a proxy. You can get this by replacing
var c = new Category { CategoryName = "Testcat" };
与
var c = _db.Categories.Create();
c.CategoryName = "Testcat";
您的其他选项仍然使用没有代理的POCO,并自行创建此列表并替换
Your other option is still use a POCO without a proxy and create this list yourself and replace
c2.Products.Add(pr);
与
c2.Products = new List<Product> { pr };
这篇关于在EF4代码第一集合不是懒惰加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!