Given a simple parent -> child (CK,CK) setup like this .. I am having trouble with adding a new child object and it getting the parent reference. So I would add the object in such a way ..
var parent = new Parent{
Children = new List<Child>{
new Child{
Other = otherReference
}
}
};
Or even adding it using the Add()
method...
parent.Children.Add(new Child { Other = other });
The reference to the Parent
does not get pushed through. It just ends up as a null property. I get the following exception.
{"Cannot insert the value NULL into column 'ParentId', table 'mssql_test.Children'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
I can do this ...
new Child {
Parent = parentReference,
Other = otherReference
}
But that seems a bit redundant. My understanding is that it should be able to infer the reference by itself. If this is not possible, perhaps I am just misunderstanding. Can anyone help me? I have an outline of my code below.
Classes
class Parent {
int Id { get; set; }
IList<Child> Children { get; set; }
}
class Other {
int Id { get; set; }
}
class Child {
Parent Parent { get; set; }
Other Other { get; set; }
// other properties
}
Mapping
ChildMap() {
CompositeId()
.KeyReference(x => x.Parent, "ParentId")
.KeyReference(x => x.Other, "OtherId");
}
ParentMap(){
HasManyToMany(x => x.Children)
.AsBag()
.ChildKeyColumns.Add(new[] { "ParentId", "OtherId" })
.Inverse()
.Cascade.All())
.Table("[Test]");
}