NHibernate fluent HasMany mapping inserts NULL For

2019-05-03 09:18发布

I have an entity Company that has many Orders. I mapped these as following to each other:

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 a SQL error: "Cannot insert the value NULL into column 'CompanyID', table 'Orders'; column does not allow nulls. INSERT fails."

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

Which is a logical error because indeed I set CompanyID to be not nullable.

However with the inverse I expected CompanyID to be filled with the proper ID but by the life of me, I can't get it to work. I tried removing the Inverse (the behavior didn't change at all), changed the cascade, set the reference to be not nullable.

I even made the column nullable in the table to humor NHibernate. But that left me with an orphaned Order as it did create the Order record but left the CompanyID NULL.

This is my testcode where i made the new order:

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

Updates by the way went all fine.

Anyway, I'm hoping someone here sees what I did wrong in my mapping.

Thanks in advance.

2条回答
叼着烟拽天下
2楼-- · 2019-05-03 09:47

you forgot to set the company on the order

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

inverse only tells NH that order uses the reference to Company on the Order object to insert the Id.

查看更多
SAY GOODBYE
3楼-- · 2019-05-03 09:49

Add this first!!!

test.Orders.Add(new Order("test"){Company = test});
查看更多
登录 后发表回答