【问题标题】:Update Child ForeignKey using Nhibernate Stateless Session使用 Nhibernate 无状态会话更新子外键
【发布时间】:2011-11-13 05:42:54
【问题描述】:

我了解在使用无状态会话时,必须明确保存对象关联(子)

如果我有以下对象:

public class Parent()
{
    public int Id {get;set;}
    public string Name {get;set;}
    public IList<Child> Childs {get;set;}
}

public class Child()
{
    public int Id {get;set;}
    public string Name {get;set;}
}

我修改了一个父实例并添加了一个子实例,然后使用以下语句保存父实例和子实例:

statelesssession.Update(parentInstance);
statelesssession.Insert(parentInstance.Childs.Last());

这样做会成功更新父记录并创建子记录,但是子表中的字段 Parent_Id 保持为空,因此不会记录关联。

如何使用无状态会话手动记录关联?

【问题讨论】:

    标签: nhibernate orm stateless-session


    【解决方案1】:

    我在Child 上没有看到指向Parentmany-to-one 属性。这就是 NHibernate 用于保存 Parent_id 列的方法。你需要:

    public class Child
    {
        public int Id {get;set;}
        public Parent Parent {get;set;} // this is missing
        public string Name {get;set;}
    }
    

    ... 和相应的 NHibernate 映射。此外,请确保在将子级添加到父级时设置 child.Parent 的值。

    另一件事,考虑到您描述的事件顺序(“我创建了一个父实例并为其添加一个子实例”),我原本希望看到父级的 Insert 而不是 Update

    【讨论】:

    • 是的,但我希望这种关系是单向的,只有父母对孩子。我的意思是如何通过单向关系来实现这一点。
    • 如果您没有对父类的引用,您至少需要一个映射到子类中父 id 的字段。就像那时的任何其他专栏一样。
    猜你喜欢
    • 2011-03-22
    • 2012-11-06
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2011-09-01
    • 1970-01-01
    相关资源
    最近更新 更多