C# NHibernate合并前保存嵌套的临时对象

C# NHibernate合并前保存嵌套的临时对象,c#,nhibernate,fluent-nhibernate,C#,Nhibernate,Fluent Nhibernate,是否有办法在嵌套对象中保存瞬态对象 问题在于对象引用与会话中的对象引用不同,因为模型来自反序列化的json,然后投影到实体中。因此,我需要在NHibernate会话上使用Merge 假设我们有这个简化模型 class Product { public int Id {get; protected set;} Public List<ProductVariant> ProductVariants {get; set;} } class ProductVariant {

是否有办法在嵌套对象中保存瞬态对象

问题在于对象引用与会话中的对象引用不同,因为模型来自反序列化的json,然后投影到实体中。因此,我需要在NHibernate会话上使用Merge

假设我们有这个简化模型

class Product
{
    public int Id {get; protected set;}
    Public List<ProductVariant> ProductVariants {get; set;}
}
class ProductVariant
{
    public int Id {get; protected set;}
    //more stuff nested deeper
}
因此:

我知道我可能会做一些类似的事情:

Foreach (productVariant : Product.ProductVariants){
    if( productVariant.Id == 0)
        sessiont.save(productVariant);
}
session.Merge(Product);
但有没有一种方法可以告诉我们,如果暂时的对象只是保存

因为,假设您要保存的对象是深度嵌套的,只需在整个嵌套对象中查找0的ID就有点糟糕了

编辑:

看起来我可以重写equals方法来检查Id是否相同,是否属于同一类型的对象,但我内心的某些东西说这是个坏主意。即使集合Id受保护。然而,过度使用Equals方法意味着我可以使用SaveOrUpdate,这是更好的选择

比如:

类产品
{
public int Id{get;protected set;}
公共列表变量{get;set;}
公共覆盖布尔等于(对象对象对象)
{
if(obj==null | | GetType()!=obj.GetType())
返回false;
产品其他产品=(产品)obj;
返回otherProduct.Id==Id
}
}
类ProductVariant
{
public int Id{get;protected set;}
//更多的东西嵌套得更深
公共覆盖布尔等于(对象对象对象)
{
if(obj==null | | GetType()!=obj.GetType())
返回false;
ProductVariant otherProduct=(ProductVariant)obj;
返回otherProduct.Id==Id
}
}

至少他们在这里说的是:在问题2下,您需要将
产品
映射中的
产品变体
列表级联。如果新的
ProductVariant
尚未持久化,NHibernate将添加它


如果所有设置都正确,则不需要调用任何
SaveOrUpdate()
Merge()
方法。

已使用cascade.all,肯定是在某个地方出错了else@HenrikBøgelundLavstsen在这里遇到了同样的问题,并且已经将所有问题级联
session.SaveOrUpdate(Product) //wont work, different object reference to the same identity
session.Merge(Product) //Wont work, there is a transient object
Foreach (productVariant : Product.ProductVariants){
    if( productVariant.Id == 0)
        sessiont.save(productVariant);
}
session.Merge(Product);
class Product
{
    public int Id {get; protected set;}
    Public List<ProductVariant> ProductVariants {get; set;}

    public override bool Equals(Object obj) 
    {

       if (obj == null || GetType() != obj.GetType()) 
       return false;

       Product otherProduct = (Product)obj;
       return otherProduct.Id == Id
    }
}
class ProductVariant
{
    public int Id {get; protected set;}
    //more stuff nested deeper
    public override bool Equals(Object obj) 
    {

       if (obj == null || GetType() != obj.GetType()) 
       return false;

       ProductVariant otherProduct = (ProductVariant)obj;
       return otherProduct.Id == Id
    }
}