流畅的NHibernate:如何创建一对多的双向映射?(Fluent NHibernate: How to create one-to-many bidirectional mapping?)
基本问题 :如何在Fluent NHibernate中创建双向一对多地图?
细节:
我有一个父对象有很多孩子。 在我的情况下,孩子没有父母是没有意义的,所以在数据库中,我想要父对象的外键具有NOT NULL约束。 我从Fluent NHibernate映射自动生成我的数据库。
我有一个父母,许多孩子对象像这样:
public class Summary { public int id {get; protected set;} public IList<Detail> Details {get; protected set;} } public class Detail { public int id {get; protected set;} public string ItemName {get; set;} /* public Summary Owner {get; protected set;} */ //I think this might be needed for bidirectional mapping? }
这是我开始的映射:
public class SummaryMap : ClassMap<Summary> { public SummaryMap() { Id(x => x.ID); HasMany<Detail>(x => x.Details); } } public class DetailMap : ClassMap<Detail> { public DetailMap() { Id(x => x.ID); Map(x => x.ItemName).CanNotBeNull(); } }
在Detail表中,Summary_id应该不为空,因为在我的情况下,将Detail对象未附加到摘要对象是没有意义的。 但是,仅使用HasMany()映射则将Summary_id外键留空。
我在NHibernate文档( http://www.hibernate.org/hib_docs/nhibernate/html/collections.html )中发现“如果父项是必需的,请使用双向一对多关联”。
那么如何在Fluent NHibernate中创建双向一对多地图?
Basic question: How to I create a bidirectional one-to-many map in Fluent NHibernate?
Details:
I have a parent object with many children. In my case, it is meaningless for the child to not have a parent, so in the database, I would like the foreign key to the parent to have NOT NULL constraint. I am auto-generating my database from the Fluent NHibernate mapping.
I have a parent with many child objects like so:
public class Summary { public int id {get; protected set;} public IList<Detail> Details {get; protected set;} } public class Detail { public int id {get; protected set;} public string ItemName {get; set;} /* public Summary Owner {get; protected set;} */ //I think this might be needed for bidirectional mapping? }
Here is the mapping I started with:
public class SummaryMap : ClassMap<Summary> { public SummaryMap() { Id(x => x.ID); HasMany<Detail>(x => x.Details); } } public class DetailMap : ClassMap<Detail> { public DetailMap() { Id(x => x.ID); Map(x => x.ItemName).CanNotBeNull(); } }
In the Detail table, the Summary_id should be Not Null, because in my case it is meaningless to have a Detail object not attached to the summary object. However, just using the HasMany() map leaves the Summary_id foreign key nullable.
I found in the NHibernate docs (http://www.hibernate.org/hib_docs/nhibernate/html/collections.html) that "If the parent is required, use a bidirectional one-to-many association".
So how do I create the bidirectional one-to-many map in Fluent NHibernate?
原文:https://stackoverflow.com/questions/310641