Fluent-NHibernate:如何创建具有独特约束的多对多关系
我想创建多对多关系,但我想在新表(MessageReceivers)中对两列(AdvanceMessageId,UserId)有一个唯一的约束:
mapping.HasManyToMany(x => x.Receivers)
.WithParentKeyColumn("AdvanceMessageId")
.WithChildKeyColumn("UserId")
.Cascade.All()
.LazyLoad()
.WithTableName("MessageReceivers");
感谢帮助
I want to create a many to many relationship, but I want to have in the new table(MessageReceivers) a unique contraint on both columns (AdvanceMessageId,UserId):
mapping.HasManyToMany(x => x.Receivers)
.WithParentKeyColumn("AdvanceMessageId")
.WithChildKeyColumn("UserId")
.Cascade.All()
.LazyLoad()
.WithTableName("MessageReceivers");
Thanks for help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
旧帖子...但万一其他人到达这里寻找答案:
您需要将 .AsSet() 添加到 HasManyToMany 映射定义中。
即,
这将在使用两列的链接表上设置一个唯一的复合主键约束。
(聚集索引)
缺点是 AsSet() 不能与 IList 类型的集合属性一起使用,因此不进行强制转换就没有 for 循环。
我一直在使用 ICollection 并将它们实例化为我的应用程序的 HashSet,并且效果很好。
有关使用 Fluent Nhibernate 进行集合管理的更多信息:
列表:实体的有序集合,允许重复。在代码中使用 .net IList。索引列需要在 NHibernate 中进行映射。
Set:唯一实体的无序集合,不允许重复。在代码中使用 Iesi.Collection.ISet。重写 GetHashCode 和 Equals 以指示重复的业务定义非常重要。可以通过定义 orderby 或定义比较器来排序,从而产生 SortedSet 结果。
Bag:实体的无序列表,允许重复。在代码中使用 .net IList。列表的索引列未映射,且不受 NHibernate 认可。
Old post... but in case someone else arrives here looking for the answer:
You need to add .AsSet() to the HasManyToMany mapping definintion.
i.e.
This will setup an unique, composite primary key constraint on the link table that uses both columns.
(clustered index)
The down side is AsSet() cannont be used with collection properties of type IList, so no for loops without casting.
I have been using ICollection and instantiating them as HashSet for my applications and it works well.
More info on collection management with Fluent Nhibernate:
List: Ordered collection of entities, duplicate allowed. Use a .net IList in code. The index column will need to be mapped in NHibernate.
Set: Unordered collection of unique entities, duplicates not allowed. Use Iesi.Collection.ISet in code. It is important to override GetHashCode and Equals to indicate the business definition of duplicate. Can be sorted by defining a orderby or by defining a comparer resulting in a SortedSet result.
Bag: Unordered list of entities, duplicates allowed. Use a .net IList in code. The index column of the list is not mapped and not honored by NHibernate.
您还应该映射关系的反面,例如
在最新的 Fluent NHibernate 中,您必须更改
WithTableName ->表格
WithParentKeyColumn -> ParentKeyColumn
WithChildKeyColumn -> 父键列
WithChildKeyColumn -> ChildKeyColumn
You should also map the inverse side of the relationship like
In newest Fluent NHibernate you will have to change
WithTableName -> Table
WithParentKeyColumn -> ParentKeyColumn
WithChildKeyColumn -> ChildKeyColumn