2016-04-29 68 views
2

我正在構建一個MultiLingual應用程序,其中包含一些動態翻譯。因此,我選擇爲產品製作單獨的表格,其中包括翻譯。NHibernate不插入兒童

不,我無法插入翻譯,他們是產品的一部分。插入哪個。

<class name="Product" table="Product"> 
    <id name="Id"> 
     <generator class="native" /> 
    </id> 
    <property name="SomeOtherStuff" column="SomeOtherStuff" /> 
    <set name="NaamTranslations" cascade="all"> 
     <key column="ProductId" not-null="true" /> 
     <one-to-many class="ProductTranslation" /> 
    </set> 
    </class> 

    <class name="ProductTranslation" 
     table="ProductTranslation" lazy="false"> 
    <id name="Id"> 
     <generator class="native" /> 
    </id> 
    <many-to-one name="Product" column="ProductId" not-null="true" 
       index="UQ_ProductTranslation" class="Product" 
       cascade="all-delete-orphan" /> 
    <property name="CultureCode" column="LanguageCode" 
       not-null="true" index="UQ_ProductTranslation" /> 
    <property name="Name" column="Name" not-null="true" /> 
    </class> 

我的猜測是這個問題是在NHibernate的配置中的某個地方。因爲我可以在整個代碼中遵循產品的創建。此外,我還將show_sql放在了上面,它顯示了產品的創建,但缺少ProductTranslations的插入。

INSERT INTO dbo.Product (SomeOtherStuff) VALUES (@p0); 
select SCOPE_IDENTITY(); @p) = 'Hello this is a test' [Type: String (4000)] 

回答

0

上面的映射應該工作。它只會生成並不總是想要的SQL語句。

  1. 插入父產品
  2. 插入子表ProductTranslation,沒有提及產品表(在ProductId列必須可爲空)
  3. 更新與ProductId參考子表

所以,這個有點複雜的SQL語句即使對於這種C#任務也可以工作

var p = new Product(); 
var tr1 = new ProductTranslation(); 
var tr2 = new ProductTranslation(); 
p.NaamTranslations.Add(tr1); 
p.NaamTranslations.Add(tr2); 

session.Save(p); 

爲了避免那些插入和更新,並且只有一個INSERT,我們可以使用inverse映射。這將是就像這

<class name="Product" table="Product"> 
    ... 
    <set name="NaamTranslations" cascade="all" inverse="true"> 

,但現在我們必須設置參考兩側C#

var p = new Product(); 
var tr1 = new ProductTranslation(); 
var tr2 = new ProductTranslation(); 
p.NaamTranslations.Add(tr1); 
p.NaamTranslations.Add(tr2); 

// too soon - relation back to product is missing 
//session.Save(p); 

// assign reference 
tr1.Product = p; 
tr2.Product = p; 
// now cascade will work 
session.Save(p); 

的NHibernate將現:

  1. 插入父
  2. 插入全記錄成小孩(以後不再更新)