C# 保存记录时不能在外键中插入null(一对多关系)

C# 保存记录时不能在外键中插入null(一对多关系),c#,nhibernate,asp.net-mvc-4,C#,Nhibernate,Asp.net Mvc 4,我要学习班级和班级之间的一对多关系 EstimateVersion.cs private ISet<Template> _templates; public virtual ISet<Template> Templates { get { return _templates ?? (_templates = new HashedSet<Template>()); } set { _templates = value; } } public v

我要学习班级和班级之间的一对多关系

EstimateVersion.cs

private ISet<Template> _templates;
public virtual ISet<Template> Templates
{
    get { return _templates ?? (_templates = new HashedSet<Template>()); }
    set { _templates = value; }
}
public virtual EstimateVersion EstimateVersion { get; set; }
以下是如何在映射文件中定义它们之间的关系:

EstimateVersion.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>
<many-to-one name="EstimateVersion" class="EstimateVersion" column="EstimateVersionId" />
插入估计版本的查询运行良好,但在插入模板记录时,它尝试将null插入到EstimateVersionId中,并抛出错误,因为它不可为null。(我认为如果它是可以为null的,它会首先将它作为null插入,然后用正确的值更新它)


我怎样才能纠正这个问题呢?

正如秘密松鼠所说,线路应该是相反的。通过首先在模板对象上设置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
template.EstimateVersion = version;
Repository.Save(template);

你肯定要在保存模板之前更新它吗?我不明白你的意思..我刚刚看到最后两行代码就够了,看起来应该是相反的。。。先设置版本,然后保存?尝试执行@Secret Squirrel建议的操作。而不是
Repository.Save(模板);template.EstimateVersion=版本
try
template.EstimateVersionId=version.VersionId;保存(模板)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);