有没有办法将分离的实体更新回数据库,以及选择相关实体?这意味着我们必须
问题是如果我们尝试对分离的实体做任何事情,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