1

I'm trying to batch insert some entities in a chain of foreign key entities. Entity ID is mapped as identity.

I have a list of A, with B as property, and B has C as property.

When I trying to commit the changes to database, it give me error: "object references an unsaved transient instance - save the transient instance before flushing or set cascade action for the property to something that would make it autosave. "

class Program
{
    static viod Main (string[] args)
    {
        var list = new List<A>{
            new A{
                B = new B{
                    C = new C{
                        Name = "test";
                    }
                }
            },
            new A{
                B = new B{
                    C = new C{
                        Name = "test";
                    }
                }
            },
        };

        foreach(var a in list)
        {
            statelessSession.Insert(a);
            //session.Save(a);    // I have tried this as well, does not work neither.
        }
        transaction.Commit();
    }
}

public class A : BaseEntity
{
    public virtual B B{get; set;}
}
public class B : BaseEntity
{
    public virtual C C{get; set;}
}

public class C : BaseEntity
{
    public virtual string Name{get; set;}
}

public class BaseEntity
{
    public virtual long ID {get; set;}
}
4

1 回答 1

0

你不能。

使用 Identity 需要 NHibernate 选择最后一个插入,以便获得与下一条记录相关联的 ID。

http://www.philliphaydon.com/2011/09/the-benefits-of-letting-the-orm-generate-the-identity-part-1/

您需要使用 Guid Comb 或 HiLo。

这些允许 NHibernate 自己生成密钥并在批处理和插入之前创建所有关联。

于 2013-11-14T16:08:07.310 回答