所以我有一个名为order的父对象和一个名为orderLineItems的子对象集合,其中Cascade在nHibernate中设置为All-Delete-orphan。这是我的代码。
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();
}
transaction.Commit();
失败并显示错误:
NHibernate.HibernateException:拥有实体实例不再引用cascade =“all-delete-orphan”的集合
另外,all和all-delete-orphan与示例之间有什么区别。
答案 0 :(得分:4)
你有:
order.OrderLineItems.Clear();
order.OrderLineItems = order.OrderLineItems == null
? new List<IOrderLineItem> { orderLineItem1 }
: new List<IOrderLineItem>(order.OrderLineItems) { orderLineItem1 };
首先,如果order.OrderLineItems为null,那么order.OrderLineItems.Clear()将抛出NullReferenceException,其次问题就出现了,因为你要为order.OrderLineItems分配一个新List,所以NHibernate不知道要级联什么删除。要使其工作,只需将第二行更改为:
order.OrderLineItems.Add(orderLineItem1);
答案 1 :(得分:0)
在映射中 - 将集合标记为inverse()
HasMany(x=>x.OrderLineItems)
.Inverse();