3
votes

I have a database with a ProbateCases table and a Properties table. The Properties table has a foreign key to the ProbateCases table called ProbateCaseId, so the relationship between ProbateCases and Properties is one-to-many.

My domain layer has a ProbateCase class and a Property class. The ProbateCase class has a collection of Properties defined as follows:

private IList<Property> _properties = new List<Property>();
public virtual IEnumerable<Property> Properties { get { return _properties; } }
public virtual Property AddProperty()
    {
      Property property = new Property();
      _properties.Add(property);
      return property;
    }

The corresponding part of the Fluent NHibernate mapping looks like this:

HasMany(x => x.Properties).Where("Deleted = 0").KeyColumn("ProbateCaseId").Cascade.All().Access.CamelCaseField(Prefix.Underscore);

Note that the association is unidirectional - the ProbateCase class has a collection of Properties, but the Property class does not have a ProbateCase member.

I'm finding that querying works fine - NHibernate is creating the appropriate SQL to get Properties with the appropriate ProbateCaseId value.

However, when I save a ProbateCase to which I have added a new Property, the INSERT SQL does NOT contain a value for the foreign key field - so I get a SQL Exception complaining of a NULL value in the foreign key:

INSERT INTO AdminOverview.Properties (PropertyName) VALUES ('Name of property') -- Where the hell is the ProbateCaseId field value???

Should I be expecting NHibernate to populate the foreign key value itself, or is there something else I should be doing?

1

1 Answers

3
votes

From http://nhibernate.info/doc/nh/en/index.html#collections-onetomany:

Very Important Note: If the column of a association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true". See the discussion of bidirectional associations later in this chapter.