Reputation: 2328
So I have a parent object called order and a collection of child objects called orderLineItems with Cascade set to All-Delete-orphan in nHibernate. Here is my code.
using( var session = _sessionManager.GetSession())
using (var transaction = session.BeginTransaction())
{
var order = _repository.GetOrderEagerlyByOrderId(session, fromDb.Id);
var now = DateTime.Now;
const string user = "GNB\\Username";
var future = now.AddYears(1);
var taxType = new TaxType(0, "Code", "AlternateNameE", "AlternateNameF", "NameE", "NameF", "DescriptionE", "DescriptionF", 13, now, future, user, now, user, now);
var _serviceCatRep = new ServiceCatalogueRepository();
var serviceCatalogueItem = _serviceCatRep.GetServiceCatalogueItemByCode(session, "VR-PASS");
var orderLineItem1 = new OrderLineItem(0, null, "DescriptionE", "DescriptionF", 1, 10, null, null, 5, false, serviceCatalogueItem, null, user, now, user, future);
order.OrderLineItems.Clear();
order.OrderLineItems = order.OrderLineItems == null ? new List<IOrderLineItem> { orderLineItem1 } : new List<IOrderLineItem>(order.OrderLineItems) { orderLineItem1 };
_repository.SaveOrUpdate(session, order);
transaction.Commit();
}
It fails on transaction.Commit();
with the error:
NHibernate.HibernateException : A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance
Also, what are the differences between all and all-delete-orphan with an example.
Upvotes: 4
Views: 4231
Reputation: 5679
You've got:
order.OrderLineItems.Clear();
order.OrderLineItems = order.OrderLineItems == null
? new List<IOrderLineItem> { orderLineItem1 }
: new List<IOrderLineItem>(order.OrderLineItems) { orderLineItem1 };
firstly if order.OrderLineItems is null then the order.OrderLineItems.Clear() will throw a NullReferenceException, secondly the problem is arising because you're assigning a new List to order.OrderLineItems so NHibernate doesn't know what to cascade the delete for. To get it to work, just change the second line to:
order.OrderLineItems.Add(orderLineItem1);
Upvotes: 4
Reputation: 18909
In you mapping - mark the collection as inverse()
HasMany(x=>x.OrderLineItems)
.Inverse();
Upvotes: 0