简而言之,问题是,当将子对象添加到父对象的集合属性而未明确设置子对象的父属性时,插入将失败。我们举个例子: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