I have a domain model where a Order
has many LineItem
s. When I create a new Order
(with new LineItems
) and use PersistenceSpecification
to test the mapping, NHibernate throws a PropertyValueException:
var order = new Order() { LineItems = new List<LineItem>() };
order.LineItems.Add(new LineItem());
new PersistenceSpecification<Order>(session)
.CheckList(o => o.LineItems, order.LineItems) // PropertyValueException
.VerifyTheMappings();
NHibernate.PropertyValueException: not-null property references a null or transient value LineItem._Order.LineItemsBackref
Domain model
public class Order {
public virtual Guid Id { get; set; }
public virtual ICollection<LineItem> LineItems { get; set; }
[...]
}
public class LineItem {
public virtual Guid Id { get; set; }
[...]
}
A LineItem
on its own is not interesting, and they will never appear without a Order
, so the relationship is unidirectional.
Fluent Mappings/Schema
// OrderMap.cs
Id(x => x.Id).GeneratedBy.GuidComb();
HasMany(x => x.LineItems)
.Not.Inverse()
.Not.KeyNullable()
.Not.KeyUpdate()
.Cascade.AllDeleteOrphan();
// LineItemMap.cs
Id(x => x.Id).GeneratedBy.GuidComb();
// Schema
CREATE TABLE Orders ( Id uniqueidentifier NOT NULL, /* ... */ )
CREATE TABLE LineItems ( Id uniqueidentifier NOT NULL,
OrderId uniqueidentifier NOT NULL, /* ... */ )
The foreign key column in the LineItems table is not nullable, so based on the information in this question I specified Not.KeyNullable()
and Not.Inverse()
to prevent NHibernate from attempting to insert a LineItem
with a NULL Id
.
I'm using NHibernate 3.3.2.400 and FluentNHibernate 1.3.0.733 (the current latest versions from NuGet).