nhibernate的3.3一一对多映射逐代码更新孩子而插入 [英] nhibernate 3.3 one-to-many mapping-by-code updates children instead of inserting
问题描述
我有这样一个一对多关联我'老'的NHibernate或创建流畅的时候zilions。但我上无法使其与映射按代码
I have this one-to-many association I created zilions of times with 'old' nhibernate or fluent. But I cann't make it work with mapping-by-code
以上是类
public class Parent
{
public virtual IList<Child> Children { get; set; }
}
public class Child
{
public virtual Parent Parent { get; set; }
}
没有什么奇怪的。
Nothing odd
和这些映射类
有关家长:
Bag(x => x.Parent, m => m.Key(k => k.Column("Parent_id")));
儿童:
Child:
ManyToOne(x => x.Children, map => { map.Column("Parent_id"); map.Cascade(Cascade.All); });
如果我做了以下
var parent = new Parent();
parent.Children.Add(new Child());
session.SaveOrUpdate(parent);
我得到了家长正确的INSERT,但它增加了对任何儿童的UPDATE
I got correct INSERT for parent, but it does an UPDATE for any child added
UPDATE TableChildren
......
WHERE Id = 0 <-????
什么是我缺少什么?我敲我的头!
What's am I missing? I'm banging my head!!
推荐答案
我看到两个问题。映射似乎反转(袋
应该去孩子
,多对一
为父
)。这里的基本设置也是逆=真
。
I see two issues. The mapping seems to be inverted (Bag
should go for Children
, ManyToOne
for a Parent
). The essential setting here is also the inverse="true"
.
由于在这里详细记载:
- 的Mapping-by-Code - 设置和袋,我们应该补充一点:
- 映射逐码 - 多对一
- Mapping-by-Code - Set and Bag, we should add this:
- Mapping-by-Code - ManyToOne
儿童应该映射是这样的:
The Children should be mapped like this:
Bag(x => x.Children, m =>
m.Inverse(true);
m.Cascade(Cascade.All);
m.Key(k => k.Column("Parent_id")));
和这样的父
ManyToOne(x => x.Parent, map =>
{
map.Column("Parent_id");
});
的
逆=真
是一个这样如何指导NHibernate的,每个孩子可以管理自己。因此,一旦孩子加入到孩子
集合,我们还必须将它父
!那么NHibernate的将插入孩子一步到位正确的参考。
The inverse="true"
is a way how to instruct NHibernate, that each child can manage itself. So, once the child is added into the Children
collection, we also have to set its Parent
! NHibernate will then INSERT the child with the correct reference in one step.
这篇关于nhibernate的3.3一一对多映射逐代码更新孩子而插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!