1

Im in a bit of a jam.

Problem

NHibernate forces me to make a foreignkey column nullable, which is a very bad idea for our database and quite ugly.

Is there a work around for this?

Situation

I have the following maps (names changed for simplicity):

public class BillMap : SequenceGeneratedIdEntityMap<Bill>
{
   public BillMap()
   {
           Id(x => x.Id).GeneratedBy.Native("BILL_SEQ");
           ... (maps) ...
           HasMany<Expense>(f => f.Expense)
            .Schema("ACCOUNT")
            .Table("EXPENSE")
            .KeyColumn("BILL")
            .Cascade.All();
   }
}

public class ExpenseMap : SequenceGeneratedIdEntityMap<Expense>
{
   public ExpenseMap ()
   {
      Id(x => x.Id).GeneratedBy.Native("EXPENSE_SEQ");
      ... (maps) ...
   }
}

Using these maps I get the following from NHibernate when saving an instance of Bill:

select ACCOUNT.BILL_SEQ.nextval from dual
select ACCOUNT.EXPENSE_SEQ.nextval from dual

command 0:INSERT INTO ACCOUNT.BILL(...)
command 0:INSERT INTO ACCOUNT.EXPENSE(...)
command 0:UPDATE UPDATE.EXPENSE SET BILL = X WHERE ...

Notice 2 things here:

  1. All id's are requested from the sequences BEFORE the inserts.
  2. The foreignkey is not updated until AFTER the expense has been inserted.

This forces me to make the column nullable AND to allow updates on the table.

Ideally the update statement should not be necessary and handled some deep dark place inside NHB :).

This could be solved by making a bidirectional reference, but that would destroy my model :/.

I do believe this a returning issue for me (never found a good solution before). Are there anyone who knows of workaround?

Kind regards

Christian Mikkelsen
  • 1,661
  • 2
  • 19
  • 44

1 Answers1

0

By setting .Inverse() on your HasMany<Expense> call, NHibernate will be aware of which side is the 'parent' object. I believe that will swap the order of the inserts.

For more information:

http://wiki.fluentnhibernate.org/Getting_started#Mappings

Inverse Attribute in NHibernate

Community
  • 1
  • 1
David R. Longnecker
  • 2,897
  • 4
  • 29
  • 28
  • That it would, but that would also break my model unfortunatly :/. – Christian Mikkelsen Oct 11 '11 at 06:12
  • 1
    With that (and not calling the repositories and saving independently), perhaps ask on the NHibernate users group (http://groups.google.com/group/nhusers). If they can come up with the NH XML code, we can find a way to get it working in FNH (or submit a patch at https://github.com/jagregory/fluent-nhibernate). – David R. Longnecker Oct 11 '11 at 12:44