つまり、問題は、子オブジェクトの親プロパティを明示的に設定せずに親オブジェクトのコレクション プロパティに子オブジェクトを追加すると、挿入が失敗することです。例を見てみましょう:
注:NHibernate 3.0 beta1 を使用しています。
例: 製品カテゴリ シナリオ:
(1) データベーススキーマ:
- カテゴリ (ID、名前)
- 製品 (ID、名前、価格、CategoryId)
(2) ドメイン モデルの C# コード
public class Category
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Product> Products { get; private set; }
}
public class Product
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual decimal Price { get; set; }
public virtual Category Category { get; set; }
}
(3) マッピング
<class name="Category" table="Category">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<property name="Name" />
<bag name="Products" inverse="true" cascade="all">
<key column="CategoryId" />
<one-to-many class="Core.Product"/>
</bag>
</class>
<class name="Product" table="Product">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<property name="Name" />
<property name="Price" />
<many-to-one name="Category" column="CategoryId" />
</class>
(4) 呼び出しコード
using (var session = sessionFactory.OpenSession())
{
Category category = session.Query<Category>().FirstOrDefault();
Product product = new Product
{
Name = "test",
Price = 50
};
category.Products.Add(product);
// Here, the p.Category is null, but it should NOT be null
// And if now I commit the changes the the database,
// And exception will be thrown: Cann't insert null to column CategoryId
}
がcategory.Products.Add(product)
実行されると、product.Category
オブジェクトになるはずcategory
です! カテゴリを明示的に設定するproduct.Category
と、コミット操作は成功します。なぜこれ?NHibernate 3.0 beta1 などのバグ?