Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nhibernate HiLo id values before commit

Tags:

c#

nhibernate

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:

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

Nhibernate generates schema with table named hibernate_unique_key with columns 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.

Is there a way to assign id value to object before saving it? I guess I don't quite understand usage of hilo algorithm and it's main purpose.

like image 263
makcro Avatar asked Jul 27 '26 20:07

makcro


1 Answers

HiLo is used so that the identifier can be assigned without a roundtrip to the database. 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:

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

like image 196
Trevor Pilley Avatar answered Jul 30 '26 09:07

Trevor Pilley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!