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