我正在开发一个应用程序,用户可以通过该应用程序发送带附件的电子邮件。电子邮件和附件域对象都将 hilo 定义为 id 生成器,如下所示:
<id name="Id">
<generator class="hilo" />
</id>
Nhibernate 使用名为 hibernate_unique_key 的表生成架构,其中列为 next_hi。
当用户向电子邮件添加附件时,应用程序内部会将附件对象添加到附件列表并将其绑定(bind)到 GridView ,以便用户可以看到他们添加的内容。 或者,用户可以选择以前添加的附件并通过单击删除按钮将其从列表中删除。 问题是,由于没有对象被保存到数据库,附件的 ID 没有被分配,所以我不能唯一地识别附件 obj 以从列表中删除。
有没有办法在保存之前给对象分配 id 值?我想我不太了解 hilo 算法的用法及其主要目的。
最佳答案
使用 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
关于c# - 提交前的 Nhibernate HiLo id 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9565933/