0

简而言之,问题是,在没有显式设置子对象的父属性的情况下,将子对象添加到父对象的集合属性中时,插入会失败。举个例子:

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

示例:产品类别 Senario:

(1) 数据库模式:

  1. 类别(ID、名称)
  2. 产品(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)执行时,shouleproduct.Category是对象category!如果我明确设置product.Category类别,提交操作将成功。为什么这个?NHibernate 3.0 beta1 或其他的bug?

4

1 回答 1

1

这与记录的完全一样。

6.4. 一对多关联

NHibernate will NOT set product.Category for you. The usual way to avoid forgetting this is adding an AddProduct method to category which adds the product to the Products collection and sets the Category property.

于 2010-10-13T15:22:22.930 回答