nhibernate的:不同的对象具有相同的标识符值已经与会话相关联:2,实体: [英] nhibernate : a different object with the same identifier value was already associated with the session: 2, of entity:

查看:221
本文介绍了nhibernate的:不同的对象具有相同的标识符值已经与会话相关联:2,实体:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误,当我试图挽救这个公司的实体在我的MVC应用程序

用同样的标识值不同的对象已经与会话相关联:2的实体,:

我使用IoC容器

 私有类EStoreDependencies:NinjectModule
    {
        公共覆盖无效负载()
        {            绑定< ICompanyRepository方式>()为< CompanyRepository方式>()WithConstructorArgument(会话,
                                                                                       NHibernateHelper.OpenSession());
        }
    }

我CompanyRepository

 公共类CompanyRepository:ICompanyRepository
{
    私人的Isession _session;    公共CompanyRepository(ISession的会话)
    {
        _session =会议;
    }    公共无效更新(公司公司)
    {        使用(ITransaction事务= _session.BeginTransaction())
        {            _session.Update(公司);
            器transaction.commit();
        }
    }

}

和会话助手

 公共类NHibernateHelper
{
    私有静态ISessionFactory _sessionFactory;
    常量字符串SessionKey =MySession的;
    私有静态ISessionFactory的SessionFactory
    {
        得到
        {
            如果(_sessionFactory == NULL)
            {
                无功配置=新配置();
                configuration.Configure();
                configuration.AddAssembly(typeof运算(用户配置).Assembly);
                configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName,
                                          System.Environment.MachineName);
                _sessionFactory = configuration.BuildSessionFactory();
            }
            返回_sessionFactory;
        }
    }    公共静态的ISession的openSession()
    {
        VAR语境= HttpContext.Current;
        //。的getCurrentSession()        如果(上下文= NULL&放大器;!&安培; context.Items.Contains(SessionKey))
        {
            //返回已经打开的Isession
            返回(ISession的)context.Items [SessionKey]
        }
        其他
        {
            //在HttpContext的创建新的ISession和存储
            变种newsession的= SessionFactory.OpenSession();
            如果(上下文!= NULL)
                context.Items [SessionKey] = newsession的;            返回newsession的;
        }
    }
}

我的MVC操作

  [HttpPost]
    公众的ActionResult编辑(EStore.Domain.Model.Company公司)
    {            如果(company.Id大于0)
            {                _companyRepository.Update(公司);
                _statusResponses.Add(StatusResponseHelper.Create(常量
                    .RecordUpdated(),StatusResponseLookup.Success));
            }
            其他
            {
                company.CreatedByUserId = currentUserId;
               _companyRepository.Add(公司);
            }
        VAR视图模型= EditViewModel(company.Id,_statusResponses);
        返回视图(编辑,视图模型);
    }


解决方案

我知道这是一个有点晚了,你可能已经找到了解决办法,但也许其他人可以从中受益......

此错误是由NHibernate的,当你正在更新被保存在缓存中的实体的实例提高。基本上NHibernate的存储上的缓存你的对象,一旦你装好了,等下次调用会从缓存中得到它。如果更新实例,它是在高速缓存present NHibernate的抛出这个错误,否则可能会导致脏读和冲突有关加载对象的旧副本。
为了解决这个问题,你需要使用从缓存中删除对象的集中退出的方法,如:

 公众的ActionResult编辑(EStore.Domain.Model.Company公司)
{        如果(company.Id大于0)
        {
            ** ISession.Evict(公司)**
            _companyRepository.Update(公司);

希望这有助于。

I am getting the following error when i tried and save my "Company" entity in my mvc application

a different object with the same identifier value was already associated with the session: 2, of entity:

I am using an IOC container

private class EStoreDependencies : NinjectModule
    {
        public override void Load()
        {

            Bind<ICompanyRepository>().To<CompanyRepository>().WithConstructorArgument("session",
                                                                                       NHibernateHelper.OpenSession());
        }
    }

My CompanyRepository

public class CompanyRepository : ICompanyRepository
{
    private ISession _session;

    public CompanyRepository(ISession session)
    {
        _session = session;
    }    

    public void Update(Company company)
    {

        using (ITransaction transaction = _session.BeginTransaction())
        {

            _session.Update(company);
            transaction.Commit();
        }
    }

}

And Session Helper

public class NHibernateHelper
{
    private static ISessionFactory _sessionFactory; 
    const string SessionKey = "MySession";


    private static ISessionFactory SessionFactory
    {
        get
        {
            if (_sessionFactory == null)
            {
                var configuration = new Configuration();
                configuration.Configure();
                configuration.AddAssembly(typeof(UserProfile).Assembly);
                configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName,
                                          System.Environment.MachineName);
                _sessionFactory = configuration.BuildSessionFactory();
            }
            return _sessionFactory;
        }
    }

    public static ISession OpenSession()
    {
        var context = HttpContext.Current;
        //.GetCurrentSession()

        if (context != null && context.Items.Contains(SessionKey))
        {
            //Return already open ISession
            return (ISession)context.Items[SessionKey];
        }
        else
        {
            //Create new ISession and store in HttpContext
            var newSession = SessionFactory.OpenSession();
            if (context != null)
                context.Items[SessionKey] = newSession;

            return newSession;
        }
    }
}

My MVC Action

    [HttpPost]
    public ActionResult Edit(EStore.Domain.Model.Company company)
    {

            if (company.Id > 0)
            {

                _companyRepository.Update(company);
                _statusResponses.Add(StatusResponseHelper.Create(Constants
                    .RecordUpdated(), StatusResponseLookup.Success));
            }
            else
            {
                company.CreatedByUserId = currentUserId;
               _companyRepository.Add(company);
            }


        var viewModel = EditViewModel(company.Id, _statusResponses);
        return View("Edit", viewModel);
    }

解决方案

I know this is a bit late and you might already found the solution, but maybe others could benefit from it...

This error is raised from nHibernate when you are updating an instance of an Entity that is saved on the Cache. Basically nHibernate stores your objects on the cache once you loaded it, so next calls would get it from the cache. If you update an instance that is present on the cache nHibernate throws this error otherwise it could cause dirty reads and conflicts regarding loading the old copy of the object. To get around this, you need to remove the object from the cache using the Evict method like:

public ActionResult Edit(EStore.Domain.Model.Company company) 
{ 

        if (company.Id > 0) 
        { 
            **ISession.Evict(company);**
            _companyRepository.Update(company);

Hope this helps.

这篇关于nhibernate的:不同的对象具有相同的标识符值已经与会话相关联:2,实体:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆