简体   繁体   English

提交前Nhibernate HiLo id值

[英]Nhibernate HiLo id values before commit

I'm developing an app through which users can send email messages with attachments. 我正在开发一个应用程序,用户可以通过该应用程序发送带附件的电子邮件。 Both Email and Attachment domain objects have hilo defined as id generator as follows: 电子邮件和附件域对象都将hilo定义为id生成器,如下所示:

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

Nhibernate generates schema with table named hibernate_unique_key with columns next_hi. Nhibernate使用名为hibernate_unique_key的表生成模式,其中列为next_hi。

When user adds attachment to the email, internally app adds attachment object to list of attachments and binds it to grid view so users can see what they added. 当用户向电子邮件添加附件时,内部应用程序会将附件对象添加到附件列表并将其绑定到网格视图,以便用户可以看到他们添加的内容。 Optionally users can select previously added attachment and remove it from the list by clicking remove button. 用户可以选择以前添加的附件,然后单击“删除”按钮将其从列表中删除。 The problem is, since non of the objects are saved to database, id's of attachments have not been assigned so I cant uniquely identify attachment obj to remove from list. 问题是,由于没有将对象保存到数据库,因此尚未分配附件的ID,因此我无法唯一地标识要从列表中删除的附件obj。

Is there a way to assign id value to object before saving it? 有没有办法在保存之前为对象分配id值? I guess I don't quite understand usage of hilo algorithm and it's main purpose. 我想我不太了解hilo算法的用法,这是它的主要目的。

HiLo is used so that the identifier can be assigned without a roundtrip to the database. 使用HiLo以便可以在没有往返数据库的情况下分配标识符。 What you need to do is something like this (you will need to cater for removing attachments and exception handling etc): 你需要做的是这样的事情(你需要满足删除附件和异常处理等):

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();
}

Here are a couple of links that may also help you understand HiLo and NHibernate a bit better: 以下是一些链接,可以帮助您更好地理解HiLo和NHibernate:

http://ayende.com/blog/3915/nhibernate-avoid-identity-generator-when-possible 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 http://nhforge.org/blogs/nhibernate/archive/2009/03/20/nhibernate-poid-generators-revealed.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM