更新分离的实体并有条件地更新NHibernate中的相关实体

时间:2012-09-18 13:12:33

标签: nhibernate fluent-nhibernate nhibernate-mapping crud

有没有办法将分离的实体更新回数据库,以及选择相关实体?这意味着我们必须

  • 检查DB中是否存在分离的实体
  • 如果它不存在,请添加
  • 如果存在
    • 更新
    • 如果您想更新孩子,请执行此操作

问题是如果我们尝试对分离的实体做任何事情,NHibernate会抛出异常a different object with the same identifier value was already associated with the session

有一个类的对象:

Class Parent
   int          ParentID
   ICollection  Children

因为对象以分离的形式出现,我们以前在Entity Framework中做的是:

// Try to load detached entity equivalent from DB
var entityInDB = LoadFromDB(entityDetached.Id)

// If it doesnt exist in db we need to add it
if (entityInDB == null) 
   AddNewEntity(entityDetached)
else
   // First update parent entity --- NHibernate doesnt have something similar?!
   // These lines need translation to NHibernate logic
   // BEGIN
   // (ERROR in nhibernate if we try SaveOrUpdate() !)
   _context.Entry(entityInDB).CurrentValues.SetValues(entityDetached);

   // Chose whether to update children or not
   if (AlsoUpdateChildren)
   {
       // Update child values-Add new children
       foreach (childDetached in entityDetached.Children)
       {
            SaveEntity(childDetached)
       }

       // Delete leftover children that didn't 
       // come back with the detached Parent
       // (ERROR in nhibernate!)
       foreach (LeftoverEntity in (entityInDB.Children AND NOT in entityDetached.Children) )
       {
            DeleteEntity(LeftoverEntity )
       }
   }
    //  END

0 个答案:

没有答案