NHibernate Saving 0 to many-to-one column instead of null

前端 未结 2 1625
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 16:42

I have a table Donations which has a CampaignID column that relates to the Campaigns Table. I need to insert a 0 in the CampaignID column instead of Null if the Campaign is

相关标签:
2条回答
  • 2021-01-06 17:12

    Try loading the Campaign object whose DB identity is 0 from the DB. It will then be a fully persistent object. You should then be able to set it and persist the donation.

    If this works, you need to change the ID property mapping of the Campaign object. Nh is unable to determine that your transient campaign object created here :

    new Campaign() {CampaignID = 0};
    

    is actually a detached object. What you should do is add an 'unsaved value' into your mapping of say, -1. Now Nh can tell the difference between your valid detached campaign with a DB identity Id of 0, and transient new campaigns with Ids of -1. Then remember to set the Id for newly created campaigns to -1.

    0 讨论(0)
  • 2021-01-06 17:20
    1. NHibernate knows if an entity is already stored by checking the primary key. If it is 0, it is not stored. You can change this behavior in the mapping.
    2. If you try to save an entity, all the referencing entities must either cascade, or already be stored. This is important for NHibernate to take foreign keys. It can't point with the foreign key into you memory, it must be in the database, so it must be stored. If this is not the case, you get the exception message you have.

    With this information you should understand why you have the problem.

    Is the CampaignID generated with an automatic counter? Then it does not work anyway. (You can't set the id in the application.) Unless you store the Campaign with the CampaignID = 0 (see bellow).

    You can make the CampaignID a nullable int, then the unsaved value is null by default.

    Be aware that you get a Campaign with the CampaignID=0 in you database. This is a "Null Object". You need to store it, for instance after you setup the database.

    If you want to avoid the null object, you get in troubles. NHibernate conceptually don't let you access the foreign keys, it manages it for you. You probably can do some tricks ( for instance in an interceptor), but I think it is not worth the troubles. You also have to make sure that there is no foreign key constraint, which is also not nice.

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