使用 Nhibernate 无状态会话更新子外键
我知道,在使用无状态会话时,必须显式保存对象关联(子级)
如果我有以下对象:
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 保持为空,因此不会记录关联。
如何使用无状态会话手动记录关联?
I understand that while using the stateless session one must explicitly save an object association (child)
If I have the following objects:
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;}
}
I modify an instance of parent and add one child to it, I then save the parent and child using the following statements:
statelesssession.Update(parentInstance);
statelesssession.Insert(parentInstance.Childs.Last());
Doing this updates sucessfully the parent and creates the child record, however the field Parent_Id from the Child Table stays null, therefore there the association is not recorded.
How can I manually record the association using the stateless session?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在
Child
上没有看到指向Parent
的多对一
属性。这就是 NHibernate 用于保存Parent_id
列的内容。您需要:...以及相应的 NHibernate 映射。另外,请确保在将子级添加到父级时设置
child.Parent
的值。另一件事,考虑到您描述的事件顺序(“我创建父级的实例并向其添加一个子级”),我希望看到父级的
Insert
而不是更新
。I don't see a
many-to-one
property onChild
that points back toParent
. That's what NHibernate would use for saving theParent_id
column. You need:... and the corresponding NHibernate mapping. Also, make sure that you set the value of
child.Parent
when you add the child to the parent.Another thing, given the sequence of events you describe ("I create an instance of parent and add one child to it") I would have expected to see an
Insert
for the parent instead of anUpdate
.