简体   繁体   中英

Cannot insert null in foreign key when saving record (one-to-many relationship)

I have to classes and one-to-many relationship among them.

EstimateVersion.cs

private ISet<Template> _templates;
public virtual ISet<Template> Templates
{
    get { return _templates ?? (_templates = new HashedSet<Template>()); }
    set { _templates = value; }
}

Template.cs

public virtual EstimateVersion EstimateVersion { get; set; }

Following is how the relationship between them defined in the mapping files:

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>

Template.hbm.xml

<many-to-one name="EstimateVersion" class="EstimateVersion" column="EstimateVersionId" />

In my code that creates an EstimateVersion , this is how I 'let the objects know' of the relationship between them.

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;

The query that inserts the estimate version runs fine, but when inserting the template record, it tries to insert null into EstimateVersionId and throws error because it is non-nullable. (I think if it was nullable, it would first insert it as null and then update it with the correct value).

How can I correct this?

As Secret Squirrel said, the lines should be the other way around. By setting the EstimateVersion on the Template object first the update will save the foreign key link for you and will not attempt to insert a null value at all.

So the code sample would read:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM