提交前的 Nhibernate HiLo ID 值

3
我正在开发一个应用程序,用户可以通过该应用程序发送带有附件的电子邮件。电子邮件和附件领域对象都定义了hilo作为id生成器,如下所示:
<id name="Id">
  <generator class="hilo" />
</id>

Nhibernate生成带有表名为hibernate_unique_key和next_hi列的架构。
当用户在电子邮件中添加附件时,应用程序将附件对象添加到附件列表中,并绑定到网格视图,以便用户可以查看其添加的内容。选定的附件可通过单击“删除”按钮从列表中删除。问题是,由于没有将任何对象保存到数据库中,因此无法分配id以唯一标识要从列表中删除的附件对象。
是否有一种方法可以在保存该对象之前为其分配ID值?我想我不太理解hilo算法的用法和主要目的。
1个回答

4

HiLo 用于在不需要访问数据库的情况下分配标识符。您需要执行以下操作(需要处理删除附件和异常处理等):

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

这里有一些链接,可能会帮助您更好地了解HiLo和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

他是否也可以使用HiLo算法生成的分配ID,以防止多次往返?如果需要,这种策略会使添加多个附件变得困难。 - Fourth
我不确定我理解了,ID将由HiLo算法生成,并在调用session.Save()时由会话分配,但此时不会发生任何数据库访问,这使得批处理变得完美... - Trevor Pilley
我猜如果他想要在用户操作时进行事务作用域,这个方法可能有效(在我看来是一种危险的模式)。如果他将事务作用域提高到更高的层次,那么需要更多的思考。 - Fourth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接