问题
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