[英]fluent nhibernate mappings that save in both directions
我希望能夠做到以下幾點:
var child = new Child {
Name = "foo",
Parent = new Parent { Name = "bar" }
};
session.Save(child);
要么
var parent = new Parent {
Name = "foo",
Children = new List<Child> {
new Child { Name = "bar" },
new Child { Name = "baz" },
},
};
session.Save(parent);
並且在兩種情況下都可以在調用Save()
時Save()
所有創建的對象。 這是課程。 我不知道如何映射Parent
和Child
之間的一對多關系,這將有助於在一次調用Save()
保存所有創建的對象。 我希望可以使用任何一個版本,但在任何給定時間只能使用一個版本。 這背后的基本原理是我正在創建測試數據構建器,在某些情況下,從Child
端更容易連接它,在其他情況下,從Parent
端更容易連接。 因此,為什么我希望能夠在給定任一對象的情況下在兩個方向上級聯插入和刪除。 我不關心更新。 這只會用於插入數據,對應用程序運行我的測試,然后刪除數據。
以下是涉及的課程:
public class Child {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Parent Parent { get; set; }
}
public class Parent {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IEnumerable<Child> Children { get; set; }
}
public ChildMap : ClassMap<Child> {
public ChildMap() {
Id(x => x.Id);
Map(x => x.Name);
// How should I set this up?
Reference(x => x.Parent);
}
}
public ParentMap : ClassMap<Parent> {
public ParentMap() {
Id(x => x.Id);
Map(x => x.Name);
// How should I set this up ?
HasMany(x => x.Children);
}
}
為了能夠從兩側保存級聯,我們可以使用級聯設置
所以,這種映射就足夠了:
public ChildMap()
{
...
BatchSize(100); // this is the way how to solve 1 + N (good practice, mine at least)
// How should I set this up?
References(x => x.Parent) // References, not Reference
.Cascade.SaveUpdate()
;
}
public ParentMap()
{
...
BatchSize(100); // this is the way how to solve 1 + N
// How should I set this up ?
HasMany(x => x.Children)
.BatchSize(100) // no 1 + N
.Cascade.AllDeleteOrphan()
.Inverse()
;
有了這些設置,上面的方法就可以了,有一個重要的變化 - 孩子們必須知道它的父母。 因為我們使用逆...
這將有效:
var child = new Child
{
Name = "foo",
Parent = new Parent {Name = "bar"}
};
session.Save(child);
session.Flush();
session.Clear();
var persistedChild = session.Get<Child>(child.ID);
這也將(但設置child.Parent參考)
var parent = new Parent
{
Name = "foo",
Children = new List<Child>
{
new Child {Name = "bar"},
new Child {Name = "baz"},
},
};
foreach (var ch in parent.Children)
{
ch.Parent = parent; // we MUST do this, there is .Inverse()
}
session.Save(parent);
session.Flush();
session.Clear();
var persistedParent = session.Get<Parent>(parent.ID);
在這里閱讀更多有關批量大小的信息 (不是問題的一部分,但我總是使用它)
關於逆映射和引用賦值的一些其他細節
而且,為什么我們不能在.Rferences()(多對一)上使用相同的級聯NHibernate多對一級聯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.