Search code examples
c#c#-4.0nhibernatefluent-nhibernatefluent-nhibernate-mapping

Fluent Nhibernate save persisted entity twice in database


I have a base class with ID as Primary Key and 3 version numbers.

[NotNull]
public virtual int Id { get; private set; }
[NotNull]
[NotUpdatable]
public virtual int BaseVersion { get; set; }
[NotNull]
[NotUpdatable]
public virtual int MajorVersion { get; set; }
[NotNull]
[NotUpdatable]
public virtual int MinorVersion { get; set; }

Now I want to persist the object again if it gets a new version number or if it does not exist in the database.

foreach (var dataObject in unitOfWork.NewObjects)
{
  if (dataObject.Id > 0)
  {
     _transactionHelper.GetSession().SaveOrUpdate(dataObject.DeepClone());
     continue;
  }

  _transactionHelper.GetSession().SaveOrUpdate(dataObject);
}

My idea was to make a deepclone but sadly (for me) Nhibernate only updates the existing datarecord. I got some succes with

_transactionHelper.GetSession().Evict(dataObject);
_transactionHelper.GetSession().Save(dataObject.DeepClone());

But then Nhibernate Cascading features does not working properly and I get some times this exception detached entity passed to persist (what is correct).

Some Ideas? Or do i have to progamm is by myself :/

Thanks!


Solution

  • I solved this problem by writing my own mapping container which tracks the state of a relation. I think the main problem was/is that I used my own composite tables (I needed to add some values like active).

    To persist an allready persisted entity I used:

    _transactionHelper.GetSession().Evict(dataObject);
    dataObject.Id = 0;
    _transactionHelper.GetSession().Save(dataObject);
    

    It looks like this solution works very well for my problem.