2011-10-21 10 views
5

新しいアイテムを追加しようとすると、他のエンティティと1対多の関係を持つ各エンティティに対して、このエンティティに関連するアイテムのリストを定義する必要があるようです。どのようにしてNullable EntitySet <>を定義できますか?

[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のリストを持っているProductTypeエンティティを持っていることを言うことができます

Object reference not set to an instance of an object 

多くのrに1を持っているすべてのエンティティと同じ問題:Productsがnullであることを除い他の主体との闘い。どのようにして1対多の関係を表すEntitySet <>のnullを許可することができますか?

答えて

3

Productsエンティティセットのデフォルトを設定している生成コンストラクタがありません。デザイナーがあなたのために生成するものとこれを比較してください。たとえば、Northwindのための製品のコンストラクタは次のようになります。) `this._products =新しいのEntitySet ((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(); 
    } 
+0

おかげで、1、それは次のように正常に動作します=> entity.ProductType = this、(プロダクトエンティティ)=> entity.ProductType = null); ' –

+0

嬉しいです。それを手動で行う方法を学ぶ最も良い方法は、デザイナーが生成してそこから展開するものを見ることです。 –

関連する問題