0

简而言之,问题是,当将子对象添加到父对象的集合属性而未明确设置子对象的父属性时,插入将失败。我们举个例子:NHibernate 3.0 beta1双向一对多不能添加子对象

注意:我使用的是NHibernate 3.0 beta1。

实施例:产品类别塞纳里奥:

(1)数据库模式:

  1. 类别(ID,姓名)
  2. 产品(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?

+0

NH 3.0 Beta 1发布了吗?它没有在nhibernate-development上公布...... – codekaizen 2010-10-13 05:06:58

+0

是的。看这里:http://sourceforge.net/projects/nhibernate/files/ – 2010-10-13 05:28:07

回答

1

此行为与记录完全相同。

6.4. One-To-Many Associations

NHibernate的将不设置product.Category你。避免遗忘的常用方法是将AddProduct方法添加到将产品添加到Products集合并设置Category属性的类别中。

+0

这太糟糕了。我认为实体框架在这一点上做得更好。顺便说一句:我没有找到在NHibernate不会设置产品的文档中的句子。类别,请你为我复制句子,谢谢:) – 2010-10-14 02:49:33