Maintaining multiple one-to-many

后端 未结 1 404
南方客
南方客 2021-01-28 23:16

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.

相关标签:
1条回答
  • 2021-01-29 00:18

    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.

    0 讨论(0)
提交回复
热议问题