Maintaining multiple one-to-many

后端 未结 1 402
南方客
南方客 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).

    
    
        
        
    
    

    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.

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