NHibernate freely inserts HasMany NULL cards Foreign key

I have a company that has many warrants. I matched them as follows:

Company

HasMany(x => x.Orders).KeyColumn("CompanyID").Cascade.All().Inverse();

Order

References(x => x.Company).Column("CompanyID")

However, when I create a new order for the company and try to save it, I get an SQL error: "Cannot insert a NULL value in the" CompanyID "column, the" Orders "table, the column does not allow zeros. INSERT does not work."

(this is the generated SQL statement: INSERT INTO Order (Name, CompanyID) VALUES (?,?); select SCOPE_IDENTITY ()]])

Which is a logical mistake, because I really set CompanyID to non-zero.

However, on the contrary, I expected CompanyID to be populated with the proper identifier, but in life I cannot get it to work. I tried to remove the Inverse (the behavior did not change at all), changed the cascade, set the link to not null.

I even made the column null in the table for NHibernate humor. But that left me with an orphaned order, since he created an order record, but left a NULL CompanyID.

This is my test code where I made a new order:

Company test = RepositoryBase<Company>.GetById(1);
test.Orders.Add(new Order("test"));
RepositoryBase<Company>.SaveWithTransaction(test);

Updates, by the way, went fine.

In any case, I hope someone here sees what I did wrong in my mapping.

Thanks in advance.

+5
source share
2 answers

you forgot to customize the company

test.Orders.Add(new Order("test") { Company = test });

inverse NH, Order .

+4

!!!

test.Orders.Add(new Order("test"){Company = test});
+2

All Articles