【问题标题】:How to implement NHibernate batch insert entity with chain of foreign entities如何使用外国实体链实现 NHibernate 批量插入实体
【发布时间】:2013-11-14 16:04:05
【问题描述】:

我正在尝试在外键实体链中批量插入一些实体。实体 ID 被映射为身份。

我有一个 A 的列表,其中 B 作为属性,B 有 C 作为属性。

当我尝试将更改提交到数据库时,它给了我错误: “对象引用了一个未保存的瞬态实例 - 在刷新之前保存瞬态实例或将属性的级联操作设置为使其自动保存的内容。”

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

【问题讨论】:

    标签: c# nhibernate orm


    【解决方案1】:

    你不能。

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

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

    您需要使用 Guid Comb 或 HiLo。

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

    【讨论】:

    • 我已将 HiLo 实现为 stackoverflow.com/questions/11402621 但我仍然遇到同样的错误。所以,似乎我必须先“session.Save(C)”,然后是“session.Save(B)”,最后是“session.Save(A)”,然后再提交?这是正确的吗?
    猜你喜欢
    • 2021-01-09
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    相关资源
    最近更新 更多