[英]Map foreign key in Fluent NHibernate without object property
我的問題是,對於父對象和子對象是否有可能的Fluent NHibernate映射,它不需要Child對象具有Parent對象屬性? 我還沒弄明白如何將引用映射回Parent。 當我使用映射調用Create時,我得到一個異常,因為Child對象沒有所需的外鍵(在數據存儲中需要)回到Parent。
我有兩個POCO課程:
public class Parent
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Child> Childs { get; set; }
}
public class Child
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual int ParentId { get; set; }
}
還有一些映射:
public class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
this.Table("Parents");
this.Id(x => x.Id);
this.Map(x => x.Name);
this.HasMany(x => x.Childs).KeyColumn("ChildId").Cascade.AllDeleteOrphan();
}
}
public class ChildMap : ClassMap<Child>
{
public ChildMap()
{
this.Table("Childs");
this.Id(x => x.Id);
this.Map(x => x.Name);
// Needs some sort of mapping back to the Parent for "Child.ParentId"
}
}
並創建方法:
public Parent Create(Parent t)
{
using (this.session.BeginTransaction())
{
this.session.Save(t);
this.session.Transaction.Commit();
}
return t;
}
我希望能夠創建一個具有Child對象列表的Parent對象,但不能讓Child對象返回其父對象(除了Parent ID)。 我想這樣做是為了避免從Parent到Childs列表的循環引用回到Parent對象,因為這會導致JSON序列化問題。
您可以毫無問題地映射這些實體,試試這個:
public class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
this.Table("Parents");
this.Id(x => x.Id);
this.Map(x => x.Name);
this.HasMany(x => x.Childs).KeyColumn("ChildId").Cascade.AllDeleteOrphan();
}
}
public class ChildMap : ClassMap<Child>
{
public ChildMap()
{
this.Table("Childs");
this.Id(x => x.Id);
this.Map(x => x.Name);
this.Map(x => x.ParentId);
// if you have a reference of Parent object, you could map as a reference, for sample:
this.References(x => x.Parent).Column("ParentId");
}
}
當您從ISession獲取實體時,請不要將其序列化為某種格式,因為這些可以是nhibernate代替實體對象。 嘗試創建DTO(數據傳輸對象)類並將這些實體轉換為DTO對象,並對其進行序列化。 你會避免循環引用。 樣品:
public class ParentDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
/* here you just have the primitive types or other DTOs,
do not reference any Entity type*/
}
當您需要讀取值以共享序列化值時:
var dto = ISession.Query<Parent>()
.Select(x =>
new ParentDTO() {
Id = x.Id,
Name = x.Name,
ParentId = x.ParentId)
.ToList();
從數據訪問層獲取此結果並嘗試序列化,以獲取示例:
var result = Serialize(dto);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.