维护多个一对多 [英] Maintaining multiple one-to-many

查看:153
本文介绍了维护多个一对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从延迟加载可空 NHibernate中的一对一?这个问题有一个解决方案,不涉及数据库中冗余的外键。

1)在用户映射中定义一个伪造的列表。列表只能有一个或零个项目。

 < bag 
name =_ contact
table =UserContacts
lazy =true
inverse =true
cascade =all-delete-orphan>

< key column =UserId/>
<一对多等级=联系人/>
< / bag>

在联系人映射中定义一对一:

 < one-to-one name =_ userclass =Userconstrained =true/> 

在数据库中,您需要有PK Users.Id和一个(!)外键Contacts.UserID 。 2)另一个选择是在用户映射和一个FK用户中简单地具有多对一的用户.ContactId




pre> <多对一
name =_ contact
column =ContactId
cascade =all-delete-orphan
unique =true
lazy =proxy/>

无论哪种方式,您所要求的维护都是不需要的,异常是不可能的。


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...

解决方案

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).

<bag 
  name="_contact" 
  table="UserContacts" 
  lazy="true" 
  inverse="true" 
  cascade="all-delete-orphan" >

    <key column="UserId" />
    <one-to-many class="Contact" />
</bag>

In Contact mapping define one-to-one:

<one-to-one name="_user" class="User" constrained="true" />

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

<many-to-one 
   name="_contact" 
   column="ContactId" 
   cascade="all-delete-orphan" 
   unique="true" 
   lazy="proxy"/>

Either way the maintenance that you asked about is not needed and anomalies are not possible.

这篇关于维护多个一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆