如何定义Nullable EntitySet <>?

Mah*_*mal 5 c# mapping one-to-many linq-to-sql

对于当我尝试添加新项目时与其他实体具有一对多关系的每个实体,似乎我必须定义与该实体相关的这些项目列表.例如,假设我有一个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); }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试添加这样的新ProductType东西时:

ProductType newType = new ProductType { Name = "newType" };
_productRepository.Add(newType);     //InsertOnSubmit() and SaveChanges()
Run Code Online (Sandbox Code Playgroud)

它给了我一个Productsnull 的异常:

Object reference not set to an instance of an object
Run Code Online (Sandbox Code Playgroud)

所有与其他实体具有一对多关系的实体都存在同样的问题.那么如何为表示一对多关系的EntitySet <>允许null

Jim*_*ley 3

您缺少生成的构造函数设置产品实体集的默认值。将其与设计师为您生成的内容进行比较。例如,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();
    }
Run Code Online (Sandbox Code Playgroud)