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:
- All id's are requested from the sequences BEFORE the inserts.
- 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 o开发者_运维知识库f workaround?
Kind regards
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
精彩评论