NHIBERNATE 3.0 BETA1双向一到一台无法添加子对象
-
29-09-2019 - |
题
简而言之,问题是,当将子对象添加到父对象的收集属性中时 没有明确设置父属性 在子对象中,插入物将失败。让我们举个例子:
笔记: :我正在使用NHIBERNATE 3.0 BETA1。
示例:产品类别Senario:
(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
对于类别,提交操作将成功。为什么这个? NHibernate 3.0 Beta1或其他的错误?
解决方案
这完全按照记录。
NHIBERNATE不会设置 product.Category
为你。避免忘记这一点的通常方法是添加 AddProduct
类别的方法将产品添加到产品集合中并设置类别属性。
不隶属于 StackOverflow