Reputation: 14012
I'm using Fluent to map a parent collection -> child collection scenario for a framework demo I'm doing, I'm a bit of an NHibernate newbie so go easy :)
I have the following mappings for my DTOs:
public class OrderMapping : ClassMap<OrderDTO>
{
public OrderMapping()
{
Id(x => x.OrderId);
Map(x => x.OrderDate);
Map(x => x.Address);
HasMany<OrderLineDTO>(x => x.OrderLines).KeyColumn("OrderId").Not.LazyLoad();
Table("`Order`");
}
}
and
public class OrderLineMapping : ClassMap<OrderLineDTO>
{
public OrderLineMapping()
{
Id(x => x.OrderLineId);
Map(x => x.OrderId).ReadOnly();
Map(x => x.Amount);
Map(x => x.Description);
References<OrderDTO>(x => x.Order).Column("OrderId");
Table("OrderLine");
}
}
The DTO objects are set up to receive these values, and this all works fine (I've turned off LazyLoad for the child for now as I'm working on the framework and LazyLoading isn't finished).
So I open my test app - the data is loaded into two grids, with the parent and the children showing correctly
If I make changes to the child or parent object and attempt to save, I can see that the SQL generated for the parent/child save is correct and the values passed to the SQL are spot on - the only issue is that after the updates, NHib decides it wants to delete the collection? It attempts this SQL:
UPDATE OrderLine SET OrderId = null WHERE OrderId = 2
Which fails because the table has a FK from OrderLine to Order on OrderLine.OrderId = Order.OrderId with no cascade. Plus I don't understand why the collection requires a delete..
NHib throws a 'could not delete collection' error - is this because it's trying to delete the 'Order' reference from the OrderLineDTO child?
Edit:
Actually looking at the DTO it looks like on the reverse mapping from my business objects that 'Order' is not included on each OrderLineDTO so I've probably worked this out already! Hate it when I do that :)
Edit 2:
Turns out that even when correctly re-creating the object on the server side I get the same issue
any ideas?
Upvotes: 1
Views: 1179
Reputation: 14012
Figured it out - RTFM :P
In the manual:
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.
Upvotes: 3