流利的nhibernate一对多

时间:2012-10-27 09:42:07

标签: c# nhibernate fluent-nhibernate fluent-nhibernate-mapping

我有一对多的关系,无法让级联工作,一旦我设置了级联,我只是得到“对象引用未保存的瞬态实例......”。

我的映射看起来像这样

public class SharedDetailsMapping : ClassMap<SharedDetails>
{
    public SharedDetailsMapping()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        HasMany(x => x.Foos);
    }
}

public class FooMapping : ClassMap<Foo>
{
    public FooMapping()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        References(x => x.SharedDetails).Cascade.SaveUpdate();
    }
}

像这样的课程

public class Foo
{
    public Foo()
    {
        SharedDetails = new SharedDetails();
        SharedDetails.Foos.Add(this);
    }

    public Foo(SharedDetails sharedDetails)
    {
        SharedDetails = sharedDetails;
        SharedDetails.Foos.Add(this);
    }

    public virtual Guid Id { get; set; }
    public virtual SharedDetails SharedDetails { get; set; }
}

public class SharedDetails
{
    public SharedDetails()
    {
        Foos = new List<Foo>();
    }

    public virtual Guid Id { get; set; }
    public virtual IList<Foo> Foos { get; set; }
}

然后我想创建Foos而不必先保存SharedDetails,如果它是一个新的Foo,就像这样:

using (var transaction = _session.BeginTransaction())
{
    var shared = new SharedDetails();

    var fooOne = new Foo(shared);
    _session.SaveOrUpdate(fooOne);

    var fooTwo = new Foo(shared);
    _session.SaveOrUpdate(fooTwo);

    transaction.Commit();
}

无法弄清楚我做错了什么,如果我首先保存SharedDetails就行了,但这就是我有Cascade设置的原因。

1 个答案:

答案 0 :(得分:6)

SharedDetailsMapping中,修改您的HasMany以添加.Inverse()

public class SharedDetailsMapping : ClassMap<SharedDetails>
{
    public SharedDetailsMapping()
    {
        Id(x => x.Id).GeneratedBy.Identity();
        HasMany(x => x.Foos)
           .Inverse();
    }
}

这指示NHibernate Foo拥有这种关系,这将帮助它以正确的顺序保存关系中的对象(在这种情况下,SharedDetails必须先保存,所以我们有它的ID保存Foo时。

有关目的/何时使用Inverse的更多信息:NHibernate's inverse - what does it really mean?

TL; DNR版本:

如果您的班级中有双向关系(一方是HasMany,另一方是参考),则HasMany应该有.Inverse()