Nhibernate 具有相同标识符值的不同对象已与会话关联+;亚硝酸铵
我使用的是ninject mvc 3和nhibernate,当我尝试进行更新时出现了这个错误,我不明白为什么Nhibernate 具有相同标识符值的不同对象已与会话关联+;亚硝酸铵,nhibernate,Nhibernate,我使用的是ninject mvc 3和nhibernate,当我尝试进行更新时出现了这个错误,我不明白为什么 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-9fcb010
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:
NHibernate.unUniqueObjectException未由用户代码处理
消息=具有相同标识符值的不同对象已与实体卡的会话e1a7bd1f-fe1d-4c2e-a459-9fcb0106ad1d关联
来源=NHibernate
EntityName=卡
堆栈跟踪:
在NHibernate.Engine.StatefulPersistenceContext.CheckUniversity(EntityKey,Object obj)中
在NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.PerformUpdate(SaveOrUpdateEvent事件、对象实体、IEntityPersister持久化器)
在NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsDetailed处(SaveOrUpdateEvent事件)
在NHibernate.Event.Default.DefaultUpdateEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent事件)中
在NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent事件)中
在NHibernate.Impl.SessionImpl.FireUpdate(SaveOrUpdateEvent事件)上
在NHibernate.Impl.SessionImpl.Update(objectobj)上
在NhibernateRepo.cs中的ccrecondator.Framework.Data.Repository.NhibernateRepo.Update[T](T实体):第33行
在CardService.EditCard(Card Card,IList`1 RewardTiers TouseAfterCap)中的CardService.cs:第108行
在
CardController.cs:第505行中的EditCbCreditCard(CbCreditCardFrmVm)
在lambda_方法中(闭包、控制器基、对象[])
位于System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller,Object[]参数)
位于System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext ControllerContext,IDictionary`2参数)
位于System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext ControllerContext,ActionDescriptor ActionDescriptor,IDictionary`2参数)
在System.Web.Mvc.ControllerActionInvoker.c_uuDisplayClass15.b_uuu12()中
位于System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter筛选器、ActionExecutingContext预文本、Func`1 continuation)
内部异常:
我不明白为什么它仍然在nhibernate会议上。我有一个web请求,它获取卡并将其绑定到VM
然后显示在页面上。然后我调用了一个save方法,我尝试将VM绑定到一个卡域,然后尝试更新它。这是在我遇到上述错误时
但这是两个不同的调用,会话应该被释放
Bind<ISessionFactory>().ToProvider<NhibernateSessionFactoryProvider>().InSingletonScope();
Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();
Bind().ToProvider().InSingletonScope();
Bind().ToMethod(context=>context.Kernel.Get().OpenSession()).InRequestScope();
我不确定我是否需要打电话给其他人或什么
我使用工作单元,所以我添加了一个dispose方法,但不确定何时调用它,以及这是否能解决我的问题
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();
}
}
公共类UnitOfWork:IUnitOfWork,IDisposable
{
私人交易;
专用只读会话;
公共工作单元(ISession会话)
{
this.session=会话;
session.FlushMode=FlushMode.Auto;
}
///
///启动数据库事务。使用IsolationLevel.ReadCommitted
///
公共无效开始生效()
{
事务=会话.BeginTransaction(IsolationLevel.ReadCommitted);
}
///
///启动与数据库的事务。
///
///事务应在其中运行的IsolationLevel。
公共void BeginTransaction(隔离级别)
{
事务=session.BeginTransaction(级别);
}
私有布尔IsTransactionActive()
{
return transaction.IsActive;
}
///
///提交事务并写入数据库。
///
公共无效提交()
{
//确保在尝试提交之前已启动事务。
如果(!IsTransactionActive())
{
抛出新的InvalidOperationException(“哎呀!我们没有活动事务。在触发此提交之前是否发生回滚:”
+transaction.WasRolledBack+“在提交之前是否发生了提交:”+transaction.WasCommitted);
}
Commit();
}
///
///回滚对数据库的任何写入。
///
公共无效回滚()
{
如果(IsTransactionActive())
{
transaction.Rollback();
}
}
public void Dispose()//不知道在哪里调用此函数以查看它是否能解决我的问题
{
if(session.IsOpen)
{
session.Close();
}
}
[HttpPost]
公共行动结果编辑CbCard(CbCardFrmVm)
{
if(ModelState.IsValid)
{
卡=新卡
{
Id=vm.Id,//数据库中记录的Id
Country=countryService.LoadCountryById(vm.SelectedCountry)
};
CardService.EditCard(卡片、奖品至后盖);
}
ModelStateValidationWrapper=ConvertTo.ModelStateValidationWrapper(creditCardService.ValidationDictionary,ModelState);
返回Json(包装器);
}
公共作废编辑卡(卡片卡,IList rewardTiersToUseAfterCap)
{
尝试
{
unitOfWork.BeginTransaction();
nhibernateRepo.更新(信用卡);
unitOfWork.Commit();
}
捕获(ADOEX)
{
ErrorSignal.FromCurrentContext().Raise(ex);
ValidationDictionary.AddError(“DbError”,ExceptionMsgs.DbError);
unitOfWork.Rollback();
}
catch(SqlException-ex)
{
错误信号
Card card = new Card
{
Id = vm.Id, // id of the record in the database
Country = countryService.LoadCountryById(vm.SelectedCountry)
};
Card card = unitOfWork.Get<Card>(vm.Id)
card.Country = countryService.LoadCountryById(vm.SelectedCountry);