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

  • Home
  • SEARCH
  • 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 7002441
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T20:55:42+00:00 2026-05-27T20:55:42+00:00

I am using ninject mvc 3 and nhibernate and I get this error when

  • 0

I am using ninject mvc 3 and nhibernate and I get this error when I try to do an update and I don’t understand why.

NHibernate.NonUniqueObjectException was unhandled by user code
  Message=a different object with the same identifier value was already associated with the session: e1a7bd1f-fe1d-4c2e-a459-9fcb0106ad1d, of entity: Card
  Source=NHibernate
  EntityName=Card
  StackTrace:
       at NHibernate.Engine.StatefulPersistenceContext.CheckUniqueness(EntityKey key, Object obj)
       at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.PerformUpdate(SaveOrUpdateEvent event, Object entity, IEntityPersister persister)
       at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsDetached(SaveOrUpdateEvent event)
       at NHibernate.Event.Default.DefaultUpdateEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event)
       at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
       at NHibernate.Impl.SessionImpl.FireUpdate(SaveOrUpdateEvent event)
       at NHibernate.Impl.SessionImpl.Update(Object obj)
       at CCRecomendator.Framework.Data.Repository.NhibernateRepo.Update[T](T entity) in NhibernateRepo.cs:line 33
       at CardService.EditCard(Card card, IList`1 rewardTiersToUseAfterCap) in CardService.cs:line 108
       at 
   CardController.EditCbCreditCard(CbCreditCardFrmVm vm) in CardController.cs:line 505
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException: 

I can’t figure out why it would be still be in the nhibernate session. I have one web request that gets the card and binds it to VM.

It then displays on the page. I then have a save method that gets called and I try to bind VM to a Card Domain then try to update it this is when I get the above error.

These are 2 different calls though and the session should be disposed off.

  Bind<ISessionFactory>().ToProvider<NhibernateSessionFactoryProvider>().InSingletonScope();
            Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();

I am not sure if I need to call another dispose or what.

I use the unit of work so I added a dispose method but not sure when I should call it and if this will even solve my problem

public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private ITransaction transaction;
        private readonly ISession session;

        public UnitOfWork(ISession session)
        {
            this.session = session;
            session.FlushMode = FlushMode.Auto;
        }

        /// <summary>
        /// Starts a transaction with the database. Uses IsolationLevel.ReadCommitted
        /// </summary>
        public void BeginTransaction()
        {
            transaction = session.BeginTransaction(IsolationLevel.ReadCommitted);
        }

        /// <summary>
        /// starts a transaction with the database.
        /// </summary>
        /// <param name="level">IsolationLevel the transaction should run in.</param>
        public void BeginTransaction(IsolationLevel level)
        {
            transaction = session.BeginTransaction(level);
        }

        private bool IsTransactionActive()
        {
            return transaction.IsActive;
        }

        /// <summary>
        /// Commits the transaction and writes to the database.
        /// </summary>
        public void Commit()
        {
            // make sure a transaction was started before we try to commit.
            if (!IsTransactionActive())
            {
                throw new InvalidOperationException("Oops! We don't have an active transaction. Did a rollback occur before this commit was triggered: "
                                                            + transaction.WasRolledBack + " did a commit happen before this commit: " + transaction.WasCommitted);
            }

            transaction.Commit();
        }

        /// <summary>
        /// Rollback any writes to the databases.
        /// </summary>
        public void Rollback()
        {
            if (IsTransactionActive())
            {
                transaction.Rollback();
            }
        }

        public void Dispose() // don't know where to call this to see if it will solve my problem
        {
            if (session.IsOpen)
            {
                session.Close();
            }

        }


[HttpPost]
public ActionResult EditCbCard(CbCardFrmVm vm)
{
    if (ModelState.IsValid)
    {
        Card card = new Card
        {
            Id = vm.Id, // id of the record in the database
            Country = countryService.LoadCountryById(vm.SelectedCountry)
        };

        CardService.EditCard(card, rewardTiersToUseAfterCap);

    }

    ModelStateValidationWrapper wrapper = ConvertTo.ModelStateValidationWrapper(creditCardService.ValidationDictionary, ModelState);
    return Json(wrapper);
}

  public void EditCard(Card card, IList<string> rewardTiersToUseAfterCap)
    {
        try
        {
            unitOfWork.BeginTransaction();

            nhibernateRepo.Update(creditCard);

            unitOfWork.Commit();
        }
        catch (ADOException ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
            ValidationDictionary.AddError("DbError", ExceptionMsgs.DbError);
            unitOfWork.Rollback();
        }
        catch (SqlException ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
            ValidationDictionary.AddError("DbError", ExceptionMsgs.DbError);
            unitOfWork.Rollback();
        }
    }

Anyone see why it would think it is in the same session.

  • 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-27T20:55:43+00:00Added an answer on May 27, 2026 at 8:55 pm

    Even if you dispose the session it would be incorrect to create a new card to update state. Instead of

    Card card = new Card
    {
        Id = vm.Id, // id of the record in the database
        Country = countryService.LoadCountryById(vm.SelectedCountry)
    };
    

    use

    Card card = unitOfWork.Get<Card>(vm.Id)
    card.Country = countryService.LoadCountryById(vm.SelectedCountry);
    

    to get the correct state. It will give you the cached instance when available without hitting the Database

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using NHibernate and ninject in ASP.Net MVC, using this page as a
I am trying to follow this tutorial http://damianm.com/tech/nhibernate-mvc-and-ninject/ but I am running into some
I'm working on an MVC site with Entity Framework Code First, using Ninject for
I'm using Ninject with an MVC app, also using EF4.1 Code First. I'm getting
I have an asp.net-mvc website and i am using ninject for IOC and nhibernate
I'm using Ninject, Fluent NHibernate and ASP.NET MVC. Up until now everything has been
I'm using the Ninject.Web.Mvc (the MVC 2 version) add-on with ASP.NET MVC 2. This
We are using ASP.net MVC. Which of these is the best DI framework Ninject
I want to map DbConnection to an un-opened SqlConnection using Ninject . This is
I have set up a NInject (using version 1.5) binding like this: Bind<ISessionFactory>().ToMethod<ISessionFactory>(ctx =>

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.