Error when using Merge() in NHibernate: a different object with the same identifier

655 Views Asked by At

I'm using FluentNHibernate and when i make post got this error.

a different object with the same identifier value was already associated with the session

That is my Controller:

private readonly ITicketAppService _ticketAppService;
public TicketController()
    {
        ITicketAppService ticketAppService = new TicketAppService(new TicketService(new TicketRepository(), new RomaneioCodRepository(), new ParamGerarMZRepository()));

    }

public ResponseApi Post(Ticket ticket)
     {
        var result = new ResponseApi();
        try{
        //my code goes here
        //my code goes here
        //my code goes here


        _ticketAppService.Add(ticket);
       _ticketAppService.Commit();

       result.DocsSaved.AddRange(ticket.ROMANEIOs);

       }
       catch (Exception ex)
       {
         _ticketAppService.RollBack();
         result.Errors.Add(new Erro(ex));
       }
       return result;
     }

And that is my Add on RepositoryBase:

public virtual void Add(TEntity obj)
        {
            try
            {
                BeginTrasaction();
                Db.Merge(obj);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Erro ao tentar adicionar alterações. Detalhes: {0}", ex);
                throw new Exception("Erro ao tentar adicionar registro.", ex);
            }
        }

All questions as i see sayed for use Merge() cause NHibernate try save one ID from user as is already on session, but i got the same error using Merge(). And i'm also using session-per-request. And i have tried make the same on this documentation. Someone know's how can i fix that?

1

There are 1 best solutions below

2
On

You are getting the same entity from multiple places using the same session, Merge method is used for attach an entity from different session.

Read this Ayende's article.