A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance

Ok, this exception "A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance" can happen with NHibernate if you have an entity with a list of other entities with the .Cascade.AllDeleteOrphan() mapping.

If you clear the list by assigning it a new List<entity>(), this exception will appear.

Instead clear the list by using the .Clear() method.




Error 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.OrderItems.Clear();

            order.OrderItems = order.OrderItems == null ? new List<IOrderLineItem> { orderLineItem1 } : new List<IOrderLineItem>(order.OrderItems) { orderLineItem1 };

            _repository.SaveOrUpdate(session, order);
            transaction.Commit();
        }

Solution Code

order.OrderItems.Clear();

order.OrderItems = order.OrderItems == null
    ? new List<IOrderLineItem> { orderLineItem1 }
    : new List<IOrderLineItem>(order.OrderItems) { orderLineItem1 };
firstly if order.OrderItems is null then the order.OrderItems.Clear() will throw a NullReferenceException, secondly the problem is arising because you're assigning a new List to order.OrderItems so NHibernate doesn't know what to cascade the delete for. To get it to work, just change the second line to:

order.OrderItems.Add(orderLineItem1);

Comments

Popular posts from this blog

Swagger for Azure functions: Undocumented TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body. Fixed.

System.Net.Http.HttpClient' does not contain a definition for 'PostAsJsonAsync