NHibernate fluent HasMany mapping inserts NULL Foreign key

℡╲_俬逩灬. 提交于 2019-12-22 06:34:15

问题


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.


回答1:


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.




回答2:


Add this first!!!

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


来源:https://stackoverflow.com/questions/11244609/nhibernate-fluent-hasmany-mapping-inserts-null-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!