问题描述
我有一个实体公司,有很多订单。我将它们映射为如下:公司
HasMany (x => x.Orders).KeyColumn(CompanyID)。Cascade.All()。Inverse();
订单
References(x => x.Company).Column(CompanyID)
然而,当我为公司创建一个新的订单,并试图保存它,我得到一个SQL错误:不能插入NULL值列'CompanyID',表'订单';列不允许NULL,INSERT失败。 (?,?);选择SCOPE_IDENTITY()]]))
这是一个逻辑错误,因为实际上我把CompanyID设置为不可为空。
然而,与此相反,我期望CompanyID填充正确的身份证,但由我的生活,我不能得到它的工作。我尝试删除反转(行为完全没有改变),改变了级联,将参考设置为不可空。
我甚至把表中的列置空以幽默NHibernate。但是,这留下了一个孤立的订单,因为它创建订单记录,但留下了CompanyID NULL。
这是我的测试代码,我做了新订单:
Company test = RepositoryBase< Company> .GetById(1);
test.Orders.Add(new Order(test));
RepositoryBase< Company> .SaveWithTransaction(test);
更新顺便一切正常
在此先感谢您。 您忘了设置公司在订单
test.Orders.Add(new Order(test){Company = test});
$ b $ p
$ b inverse仅告诉NH,Order在Order对象上使用公司的引用来插入Id。 / p>
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.
解决方案 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.
这篇关于NHibernate流利的HasMany映射插入NULL外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!