2013-11-14 86 views
1

我試圖批量插入外鍵實體鏈中的一些實體。實體ID被映射爲身份。如何實現具有外國實體鏈的NHibernate批量插入實體

我有一個A的列表,B作爲屬性,B有C作爲屬性。

當我嘗試將更改提交到數據庫時,它給了我錯誤: 「對象引用未保存的瞬態實例 - 在刷新之前保存瞬態實例或將屬性的級聯操作設置爲使其自動保存的內容。

class Program 
{ 
    static viod Main (string[] args) 
    { 
     var list = new List<A>{ 
      new A{ 
       B = new B{ 
        C = new C{ 
         Name = "test"; 
        } 
       } 
      }, 
      new A{ 
       B = new B{ 
        C = new C{ 
         Name = "test"; 
        } 
       } 
      }, 
     }; 

     foreach(var a in list) 
     { 
      statelessSession.Insert(a); 
      //session.Save(a); // I have tried this as well, does not work neither. 
     } 
     transaction.Commit(); 
    } 
} 

public class A : BaseEntity 
{ 
    public virtual B B{get; set;} 
} 
public class B : BaseEntity 
{ 
    public virtual C C{get; set;} 
} 

public class C : BaseEntity 
{ 
    public virtual string Name{get; set;} 
} 

public class BaseEntity 
{ 
    public virtual long ID {get; set;} 
} 

回答

0

你不行。

使用身份要求NHibernate選擇最後一個插入,以便獲得與下一個記錄關聯的ID。

http://www.philliphaydon.com/2011/09/the-benefits-of-letting-the-orm-generate-the-identity-part-1/

您需要使用的Guid梳或高住低練。

這些允許NHibernate自己生成密鑰並在批處理和插入之前創建所有關聯。

+0

我已經實現了HiLo作爲http://stackoverflow.com/questions/11402621但我仍然得到同樣的錯誤。因此,似乎我必須在提交之前'session.Save(C)'1st,然後'session.Save(B)'和last'session.Save(A)'。它是否正確? –

相關問題