如何定义Nullable EntitySet<>?

时间:2011-10-21 01:58:55

标签: c# linq-to-sql mapping one-to-many

对于在尝试添加新项目时与其他实体具有一对多关系的每个实体,似乎我必须定义与此实体相关的这些项目列表。 例如,假设我有一个ProductType实体,其列表为Products,如下所示:

[Table]
public class ProductType
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int Id { get; private set; }
    [Column]
    public string Name { get; set; }

    private EntitySet<Product> _products;
    [Association(Storage = "_products", ThisKey = "Id", OtherKey = "ProductTypeId")]
    public EntitySet<Product> Products
    {
        get { return _products; }
        set { _products.Assign(value); }
    }
}

当我尝试添加新的ProductType时:

ProductType newType = new ProductType { Name = "newType" };
_productRepository.Add(newType);     //InsertOnSubmit() and SaveChanges()

它给了我一个Products为空的例外:

Object reference not set to an instance of an object

与所有与其他实体具有一对多关系的实体存在同样的问题。那么如何为EntitySet&lt;&gt;提供null?代表一对多关系

1 个答案:

答案 0 :(得分:3)

您缺少生成的构造函数,为Products实体集设置默认值。将此与设计师为您生成的内容进行比较。例如,Northwind的Product构造函数如下所示:

    public Product()
    {
        this._Order_Details = new EntitySet<Order_Detail>(new Action<Order_Detail>(this.attach_Order_Details), new Action<Order_Detail>(this.detach_Order_Details));
        this._Category = default(EntityRef<Category>);
        this._Supplier = default(EntityRef<Supplier>);
        OnCreated();
    }