维护多个一对多
是否有一种简单的方法来维护多个一对多关系,这些关系被用作伪一对一。
例如,
如果我有 2 个实体,用户和联系人,它们通过每个实体 (User. ContactId 和 Contact.UserID)。
保持每个参考点指向另一个参考点的最佳方法是什么?系统用不同的联系人更新用户是错误的,但联系人仍然引用用户...
Following on from NHibernate one-to-one vs 2 many-to-one
Is there an easy way to maintain multiple one-to-many relationships which are being used as a pseudo one-to-one.
E.g.
If I have 2 entities, User and Contact, which are related by a FK on each (User.ContactId and Contact.UserID).
What is the best way to maintain that each reference points at the other. It would be wrong for the system to update User with a different contact, but the Contact still references User...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果删除一个冗余外键,很可能根本不需要维护它。您的数据库架构不应允许类似的异常(userX 引用 contactX,但 contactX 引用 userY)。从概念上讲,用户和联系人之间存在一对一的关系。为什么 NHibernate 映射中不采用一对一的映射?如果这是因为延迟加载,则 可为空不支持 /strong> NHibernate 中的一对一?这个问题有一个解决方案,就是不涉及数据库中多余的外键。
1) 在用户映射中定义一个虚假列表。列表只能包含一项或零项。零被视为 NULL(无联系人)。
在联系人映射中定义一对一:
在数据库中,您需要有 PK Users.Id 和一个(!)外键 Contacts.UserID。
2)另一种选择是在用户映射中简单地进行多对一和一个 FK Users.ContactId
无论哪种方式,都不需要您询问的维护,并且不可能出现异常。
Most likely you don't need to maintain this at all if you remove one of redundant foreign keys. Your database schema should not allow anomalies like that (userX references contactX but contactX references userY). Conceptually you have one-to-one relationship between user and contact. Why not have one-to-one in NHibernate mappings? If this is because of lazy loading that is not supported for nullable one-to-one in NHibernate? There is a solution to this problem that does not involve redundant foreign keys in the database.
1) In User mapping define a bogus list. List can have only one or zero items. Zero is treated as NULL (no Contact).
In Contact mapping define one-to-one:
In the database you need to have PK Users.Id and one (!) foreign key Contacts.UserID.
2) Another option is to simply have many-to-one in User mapping and one FK Users.ContactId
Either way the maintenance that you asked about is not needed and anomalies are not possible.