Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7587759
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T19:45:14+00:00 2026-05-30T19:45:14+00:00

I would like to handle the case where a user is editing an object

  • 0

I would like to handle the case where a user is editing an object from a database in a Windows Forms application, makes an edit that would violate a database constraint (i.e. column unique value), saves the entity back to the database, and NHibernate throws an exception thus trashing the session.

I’m using the guidance published in the MSDN article Building a Desktop To-Do Application with NHibernate and using a session-per-presenter/form approach. At creation of the presenter, I keep a reference to the SessionFactory, create a new session, retrieve the object from the database via the session and store a reference to it [the object]. When the form is displayed, its fields are populated from the object.

When changes are made to the form and the user wishes to save the data, the object is updated from the field values, and the object is saved back to the database.

I handle stale-state exceptions where the object is altered between the time it was retrieved from the database and when it is saved back: A new session is created, the original object is loaded again, the user is informed that a conflict has occurred and is presented with his changes and what is currently in the database. He can elect to save his changes or cancel (and accept what is now stored in the database).

In the event of a constraint violation, it would seem that one of two things can happen:

  1. The object has not changed in the database where it can be reloaded into the new session.
  2. The object has also been changed in the database and no longer reflects what had been initially loaded.

However, I don’t think I can actually detect which case occurred since a stale-state exception is never thrown because the constraint exception occurred (I’ve tested this).

Handling case 1 is trivial since I can simply display an error message that says “FIELD-X has a value that is already in the DB” and pretend that nothing really bad happened. The user can change FIELD-X to a unique value and save again without having to reenter his changes.

Handling case 2 would be like handling a regular stale-state exception.

I know I can “brute force” this by keeping a copy of the original (or its values) and then comparing the two field-by-field. However, I suspect that there is a better way to handle this by leveraging NHibernate. How would you handle this?

In case it is helpful:

  • NHibernate Version: 3.2
  • Optimistic-locking using “dirty” strategy
  • .NET Framework 2.0 SP2
  • SQLite database/driver

EDIT 23 Feb – I added some example code to better illustrate what I am currently doing.

/**
 * Save handler called when user initiates save in UI.
 * 
 * Returns true when save was successful (essentially, tells the presenter
 * that the UI can be closed.
 */
private bool SaveData()
{
    try
    {
        if (this.creatingNewUserAccount)
        {
            // Do whatever is necessary to instantiate a new object.
            this.userAccount = new UserAccount();
            // and copy values from the UI into the new object.
            this.userAccount.Name = this.form.Name;
            // etc.
        }
        else
        {
            // Just copy values from the UI into the existing object
            // from the database.
            this.userAccount.Name = this.form.Name;
            // etc.
        }

        using (ITransaction tx = this.session.BeginTransaction())
        {
            this.accountRepository.store(this.userAccount);
            tx.Commit();
        }

        return true;
    }
    catch (StaleObjectStateException)
    {
        HandleStaleStateException();
        return false;
    }
    catch (ArgumentException e)
    {
        this.m_View.ShowOtherDialog(e.Message);
        return false;
    }
    catch (GenericADOException e)
    {
        HandleConstraintViolationException();
        return false;
    }
}

private void HandleStaleStateException()
{
    // The session was trashed when the exception was thrown,
    // so close it and create a new one.
    this.session.Dispose();
    this.session = this.sessionFactory.OpenSession();
    CurrentSessionContext.Bind(this.session);

    // Reload the object from the database.
    this.userAccount = LoadData();

    // Do a bunch of things that deal with informing the user
    // of the stale-state and displaying a form to merge changes.
    HandleEditConflict();
}

private void HandleConstraintViolationException()
{
    // The session was trashed when the exception was thrown,
    // so close it and create a new one.
    this.session.Dispose();
    this.session = this.sessionFactory.OpenSession();
    CurrentSessionContext.Bind(this.session);

    // Determine if trying to save a new entity or editing an existing one.
    if (this.creatingNewUserAccount)
    {
        // If saving a new entity, we don't care about the old object
        // we created and tried to save.
        this.userAccount = null;
    }
    else
    {
        // ????
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T19:45:16+00:00Added an answer on May 30, 2026 at 7:45 pm

    The ISession.Refresh(Object obj) method was what ended up working for me. The code from my question remained the same except for the final method:

    private void HandleConstraintViolationException()
    {
        // The session was trashed when the exception was thrown,
        // so close it and create a new one.
        this.session.Dispose();
        this.session = this.sessionFactory.OpenSession();
        CurrentSessionContext.Bind(this.session);
    
        // Determine if trying to save a new entity or editing an existing one.
        if (this.creatingNewUserAccount)
        {
            // If saving a new entity, we don't care about the old object
            // we created and tried to save.
            this.userAccount = null;
        }
        else
        {
            this.session.Refresh(this.userAccount);
        }
        this.form.ShowDialog("... Describe the constraint violation ...");
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to handle an OracleException thrown when my network/database connection is interrupted,
I would like to either prevent or handle a StackOverflowException that I am getting
I would like to create an exception handler for the specific case that happens
I would like to integrate with the Windows Phone 7 browser so that when
I am using Ruby on Rails 3 and I would like to handle user
I have a background task I would like to handle. The thing is that
I'm working on some Silverlight controls and I would like to explicitly handle the
I would like to create infrastructure to handle events for my opengl project. It
Ok I really would like to know how expert MVVM developers handle an openfile
How would I handle something like the below uri using ASP.NET MVC's routing capability:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.