【问题标题】:Fluent-NHibernate: How to a create a many-to-many relationship with a unique contraintFluent-NHibernate:如何创建具有唯一约束的多对多关系
【发布时间】:2010-12-15 19:02:18
【问题描述】:
我想创建多对多关系,但我想在新表 (MessageReceivers) 中对两列 (AdvanceMessageId,UserId) 都有一个独特的约束:
mapping.HasManyToMany(x => x.Receivers)
.WithParentKeyColumn("AdvanceMessageId")
.WithChildKeyColumn("UserId")
.Cascade.All()
.LazyLoad()
.WithTableName("MessageReceivers");
感谢您的帮助
【问题讨论】:
标签:
fluent-nhibernate
many-to-many
unique
【解决方案1】:
您还应该映射关系的反面,例如
mapping.HasManyToMany(x => x.Users)
.WithTableName("MessageReceivers")
.WithParentKeyColumn("UserId")
.WithChildKeyColumn("AdvanceMessageId")
.Inverse();
在最新的 Fluent NHibernate 中你将不得不改变
【解决方案2】:
旧帖子...但万一其他人到达这里寻找答案:
您需要将 .AsSet() 添加到 HasManyToMany 映射定义中。
即
mapping.HasManyToMany(x => x.Users)
.WithTableName("MessageReceivers")
.WithParentKeyColumn("UserId")
.WithChildKeyColumn("AdvanceMessageId")
.Inverse().AsSet();
这将在使用两列的链接表上设置唯一的复合主键约束。
(聚集索引)
缺点是 AsSet() 不能与 IList 类型的集合属性一起使用,因此没有强制转换就不能使用 for 循环。
我一直在使用 ICollection 并将它们实例化为我的应用程序的 HashSet,它运行良好。
有关使用 Fluent Nhibernate 进行集合管理的更多信息:
列表:实体的有序集合,允许重复。在代码中使用 .net IList。索引列需要在 NHibernate 中映射。
Set:唯一实体的无序集合,不允许重复。在代码中使用 Iesi.Collection.ISet。重载 GetHashCode 和 Equals 以指示重复的业务定义很重要。可以通过定义 orderby 或通过定义导致 SortedSet 结果的比较器进行排序。
Bag:实体的无序列表,允许重复。在代码中使用 .net IList。列表的索引列未映射,NHibernate 不支持。