簡而言之,問題是,當將子對象添加到父對象的集合屬性而未明確設置子對象的父屬性時,插入將失敗。我們舉個例子:NHibernate 3.0 beta1雙向一對多不能添加子對象
注意:我使用的是NHibernate 3.0 beta1。
實施例:產品類別塞納里奧:
(1)數據庫模式:
- 類別(ID,姓名)
- 產品(ID,名稱,價格,類別ID)
(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
shoule是對象category
!如果我明確地將product.Category
設置爲category,則提交操作將成功。 這是爲什麼? NHibernate 3.0 beta1或其他的bug?
NH 3.0 Beta 1發佈了嗎?它沒有在nhibernate-development上公佈...... – codekaizen 2010-10-13 05:06:58
是的。看這裏:http://sourceforge.net/projects/nhibernate/files/ – 2010-10-13 05:28:07