NHibernate one-to-one mapping where second table data can be null

后端 未结 2 2006
说谎
说谎 2021-01-11 16:44

I have an existing database with the table Transactions in it. I have added a new table called TransactionSequence where each transaction will ultimately have only one recor

2条回答
  •  没有蜡笔的小新
    2021-01-11 17:38

    One to one mapping in nhibernate doesn't work the way you think it does. It's designed so that you have two classes, which when persisted to their corresponding tables have the same primary keys.

    However you can make it work, but it's not pretty. I'll show you how then offer up some alternatives:

    In your Transaction hbml:

    
    

    In your Sequence html:

    
    

    This should do what you want it to do. Note the property-ref.

    The next question you're going to post on is going to ask how you get lazy loading on one-to-one associations. The answer is, you can't... well you can, but it probably won't work. The problem is that you have your foreign key on the sequence table, which means that nhibernate has to hit the database to see if the target exists. Then you can try playing around with constrained="true/false" to see if you can persuade it to lazily load the one-to-one association.

    All in all, it's going to result in a total waste of your time.

    I suggest either:

    1. Have two many-to-one associations.
    2. Have a many-to-one association with a collection on the other end.

    This will save you a lot of headaches in the long run.

提交回复
热议问题