基本问题:如何在Fluent NHibernate中创建双向一对多地图?
细节:
我有一个有很多孩子的父对象.在我的情况下,孩子没有父母,所以在数据库中,我想外键的母体有NOT NULL约束是没有意义的.我从Fluent NHibernate映射自动生成我的数据库.
我的父母有很多子对象,如下所示:
public class Summary { public int id {get; protected set;} public IListDetails {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{ public SummaryMap() { Id(x => x.ID); HasMany (x => x.Details); } } public class DetailMap : ClassMap { public DetailMap() { Id(x => x.ID); Map(x => x.ItemName).CanNotBeNull(); } }
在详细信息表中,Summary_id应该是不为空,因为在我的情况下,它是没有意义的,不附加摘要对象的明细对象.但是,只使用HasMany()映射使得Summary_id外键可以为空.
我在NHibernate的文档(发现http://www.hibernate.org/hib_docs/nhibernate/html/collections.html)认为,"如果父亲是必须的,可以使用双向one-to-many关联".
那么如何在Fluent NHibernate中创建双向一对多地图?
要在Details表中获得与非null外键列的双向关联,您可以在DetailsMap类中添加建议的Owner属性,References(...).CanNotBeNull()映射,并使Summary结束.
要避免为两个关联方向指定两个不同的外键列,可以手动指定列名,也可以为两个方向指定相同列名的方式命名属性.在这种情况下,我建议您将Details.Owner属性重命名为Details.Summary.
我通过增量生成了Summary id,以避免在插入表时出现问题,因为Summary currenty除了id之外没有列.
域:
public class Detail { public int id { get; protected set; } public string ItemName { get; set; } // Renamed to use same column name as specified in the mapping of Summary.Details public Summary Summary {get; set;} } public class Summary { public Summary() { Details = new List(); } public int id { get; protected set; } public IList Details { get; protected set; } }
制图:
public class DetailMap : ClassMap{ public DetailMap() { Id(x => x.id) .GeneratedBy.Native(); Map(x => x.ItemName) .CanNotBeNull(); References (x => x.Summary) // If you don't want to rename the property in Summary, // you can do this instead: // .TheColumnNameIs("Summary_id") .CanNotBeNull(); } } public class SummaryMap : ClassMap { public SummaryMap() { Id(x => x.id) .GeneratedBy.Increment(); HasMany (x => x.Details) .IsInverse() .AsBag(); // Use bag instead of list to avoid index updating issues } }