保存记录时不能在外键中插入null(一对多关系)
本文关键字:null 插入 一对多 关系 记录 不能 保存 | 更新日期: 2023-09-27 18:27:05
我必须类,以及它们之间的一对多关系。
估计版本.cs
private ISet<Template> _templates;
public virtual ISet<Template> Templates
{
get { return _templates ?? (_templates = new HashedSet<Template>()); }
set { _templates = value; }
}
模板.cs
public virtual EstimateVersion EstimateVersion { get; set; }
以下是如何在映射文件中定义它们之间的关系:
估计版本.hbm.xml
<set name="Templates" table="EST_TTemplate" cascade="all-delete-orphan" schema="{TRAN_USER}" inverse="true">
<key column="EstimateVersionId" />
<one-to-many class="Template" />
</set>
Template.hbm.xml
<many-to-one name="EstimateVersion" class="EstimateVersion" column="EstimateVersionId" />
在我创建EstimateVersion
的代码中,这就是我如何"让对象知道"它们之间的关系。
var version = new EstimateVersion();
//Code that inserts values into the object's properties
Repository.Save(version);
var template = new Template();
//Code that inserts values into the object's properties
Repository.Save(template);
template.EstimateVersion = version;
插入估计版本的查询运行良好,但在插入template记录时,它会尝试在EstimateVersionId中插入null并抛出错误,因为它不可为null。(我认为如果它可以为null,它会首先将其插入为null,然后用正确的值更新它)。
我该如何更正?
正如Secret Squirrel所说,行应该相反。通过首先在Template对象上设置EstimateVersion,更新将为您保存外键链接,并且根本不会尝试插入null值。
因此,代码示例将为:
var version = new EstimateVersion();
//Code that inserts values into the object's properties
Repository.Save(version);
var template = new Template();
//Code that inserts values into the object's properties
template.EstimateVersion = version;
Repository.Save(template);