2012-03-05 30 views
3

我開發一個應用程序,通過它用戶可以發送帶附件的電子郵件。電子郵件和附件域對象已經希洛定義爲ID生成如下:NHibernate的希洛ID值之前提交

<id name="Id"> 
    <generator class="hilo" /> 
</id> 

NHibernate的產生與名爲是hibernate_unique_key的列next_hi表模式。

當用戶添加附件的電子郵件,內部應用程序添加附件對象,以附件的列表並將其綁定到網格視圖,使用戶可以看到他們添加了什麼。 (可選)用戶可以選擇以前添加的附件,並通過單擊刪除按鈕將其從列表中刪除。 問題是,由於對象不被保存到數據庫中,附件ID的未分配,所以我不能唯一地識別附件OBJ從列表中刪除。

是否有指定的值id保存前的對象的方法嗎?我想我不太瞭解hilo算法的用法,它是主要目的。

回答

4

希洛用於使得所述標識符可以在不往返到數據庫進行分配。你需要做的就是這樣的事情(你將需要滿足刪除附件和異常處理等):

private void CreateNewEmail_Click(object sender, EventArgs e) 
{ 
    // start a transaction so that all our objects are saved together. 
    this.transaction = this.session.BeginTransaction(); 
    this.currentEmail = new Email(); 
} 

private void AddAttachment_Click(object sender, EventArgs e) 
{ 
    var attachment = new Attachment(); 
    // set the properties. 

    // Add it to the session so that the identifier is populated (no insert statements are sent at this point) 
    this.session.Save(attachment); 

    // Also add it to the email 
    this.currentEmail.Attachments.Add(attachment); 
} 

private void SendEmail_Click(object sender, EventArgs e) 
{ 
    // Commit the transaction (at this point the insert statements will be sent to the database) 
    this.transaction.Commit(); 
} 

這裏有幾個鏈接,也可以幫助你瞭解高住低訓和NHibernate好一點。

http://ayende.com/blog/3915/nhibernate-avoid-identity-generator-when-possible

http://nhforge.org/blogs/nhibernate/archive/2009/03/20/nhibernate-poid-generators-revealed.aspx

+0

難道他也做到這一點是由高住低練算法產生的分配的ID,以防止幾次往返?如果需要的話,這種策略會使添加多個附件變得很難批量化。 – Fourth 2012-03-05 16:12:41

+0

我不知道我跟隨,將希洛算法來生成並調用session.Save(當由會話分配的ID),但是沒有數據庫命中發生在這一點上,這使得它非常適合配料... – 2012-03-05 16:28:22

+0

我猜如果他希望他的事務範圍發生在用戶操作上(這在我看來是一種危險的模式),這是有效的。如果他的交易範圍更高,則需要多思考。 – Fourth 2012-03-05 16:32:32