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

前端 未结 5 2035
陌清茗
陌清茗 2021-01-01 11:40

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 alre

5条回答
  •  别那么骄傲
    2021-01-01 11:49

    I just encountered this and Claiton Lovato's answer didn't work. However Iko's did work. Here's a little more robust version of Iko's. Downside is x2 trips to the db - one for the Get and another for the insert/update.

    A possible solution to this is to read the object from the database, copy the fields to the object, and save it.

    public void Save(Company company)
    {
    
        Company dbCompany = null;
        //update
        if (company.Id != 0)
        {
            dbCompany = _companyRepository.Get(company.Id);
            dbCompany.PropertyToUpdate = company.PropertyToUpdate;
        }
        //insert
        else
        {
            dbDefaultFreightTerm = company;
        }
        // Save either the brand new object as an insert
        // Or update the original dbCompany object with an update
        _companyRepository.SaveOrUpdate(company);
    }
    

提交回复
热议问题