4

使用 Microsoft Visual C# 2010 Express,实体框架功能 CTP4。

根据Scott Gu 的博客,我首先使用代码尝试了 EF4 。但是在检索实体时似乎没有初始化集合。将产品添加到类别时出现空引用异常。在我见过的所有示例中,集合从未显式初始化。我错过了什么?

这是我的代码:

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

}
4

2 回答 2

0

延迟加载不适用于 POCO。你需要一个代理。你可以通过更换来得到这个

var c = new Category { CategoryName = "Testcat" };

var c = _db.Categories.Create();
c.CategoryName = "Testcat";

您的另一个选择仍然是使用没有代理的 POCO 并自己创建此列表并替换

c2.Products.Add(pr);

c2.Products = new List<Product> { pr };
于 2011-05-18T13:59:25.223 回答
-1

正如 Yury Tarabanko 的评论所说,返回的类别为空,因为您没有 c 的类别 ID,因为它尚未分配。

var c2 = _db.Categories.SingleOrDefault(i => i.CategoryName == c.CategoryName);
var pr = new Product { ProductName = "testprod" };

c2.Products.Add(pr); 

将起作用,因为您为 c.CategoryName 分配了“Testcat”的值

于 2010-08-16T17:49:30.280 回答