NHibernate在合并之前保存嵌套的临时对象

时间:2015-03-18 12:56:19

标签: nhibernate fluent-nhibernate

有没有办法在嵌套对象中保存瞬态对象。

问题是对象引用与会话内的对象引用不同,因为模型来自反序列化的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
}

保存对象包含

Product -> id = 1
        -> ProductVariants -> ProductVariant -> id = 1
                           |> ProductVariant -> id = 2
                           |> ProductVariant -> id = 0 //Transient object

这样:

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);

但是,有没有办法告诉,合并,如果瞬态对象只是保存?

原因让我们说你要保存的对象是深层嵌套的,只是为了寻找0的Ids,它会很难通过整个嵌套对象。

编辑:

看起来我可以覆盖equals方法来检查Id是否相同,并且是同一类型的对象,但是我认为这是一个坏主意。即使设置ID受到保护。但是,覆盖Equals方法意味着我可以使用SaveOrUpdate,这是更好的。

像:

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
    }
}

至少他们在这里说的是:http://nhibernate.info/blog/2009/08/23/part-5-fixing-the-broken-stuff.html问题#2

1 个答案:

答案 0 :(得分:0)

您需要在ProductVariants的映射中级联 Product列表。如果新的ProductVariant没有保留,它将添加新的SaveOrUpdate()

如果一切设置正确,则无需拨打任何Merge()或{{1}}方法。

相关问题