Typical problem - I am trying to save new parent object with nested new IEnumerable of child objects which all have reference columns to store the parent Id but I can't get NHibernate configured properly to save the children objects.
The reason it won't save is because the column on the child table that references the parent table record ID is set to not allow null. But I can't figure out the correct setup on my HasMany that will allow NHibernate to generate the parent record ID and provide that in the child records reference column.
Therefore I end up with "Cannot insert NULL into column....." errors.
So I have read a ton of Questions/Answers here on Stackoverflow, and went through Ayende Rehien's as well as Fluent's Wiki and I have tried a number of different setups to no avail (i.e. remove the inverse, different cascade options..).
Currently my Entities look like this:
public class Product
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IEnumerable<Attribute> Attributes { get; set; }
}
public class Attribute
{
public virtual int Id { get; set; }
public virtual Product Product { get; set; }
public virtual IEnumerable<AttributeValue> Values { get; set; }
}
public class AttributeValue
{
public virtual int Id { get; set; }
public virtual Attribute Attribute { get; set; }
public virtual string Value { get; set; }
}
And my Fluent mappings look like:
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.Description);
HasMany(x => x.Attributes).Inverse().Cascade.All();
}
}
public class AttributeMap : ClassMap<Attribute>
{
public AttributeMap()
{
Id(x => x.Id);
Map(x => x.Name);
References(x => x.Product);
HasMany(x => x.Values).Inverse().Cascade.All();
}
}
public class AttributeValueMap : ClassMap<AttributeValue>
{
public AttributeValueMap()
{
Id(x => x.Id);
Map(x => x.Value);
References(x => x.Attribute);
}
}
My DB schema is set to not allow nulls for the reference column on the Attributes and AttributesValues table, but I have tried it as allow null because I had read that it could be setup to go back and update but that was not the case.
I have not been able to locate why I can't save child objects and have Nhibernate save the parent ID on the referenced field. I have seen a number of examples and they never had to set a foreign key up, and reference it in the mapping.
Any thoughts?