当我使用Nhibernate 3更新子项时,子项中删除的项目不会从数据库中删除。当更新子集合时,NHibernate不删除无用的记录
案例描述如下
class Parent {
string Id;
string Name;
IList Children;
}
class Child {
int ChildId;
string Name;
string Value;
Parent parent;
}
HDM映射文件显示以下 Parent.hdm.xml
<bag name="Children" table="ClientsExt" inverse ="true" cascade="all-delete-orphan" lazy="false">
<key column="ChildId"/>
<one-to-many class="XXXX.Child, XXX"/>
</bag>
Child.hdm.xml
<many-to-one name="Parent" column="Id" class="XXXX.Parent, XXX" not-null="true"/>
让我们假设有现有的父其中将数据库中的一组儿童关联起来
Parent Table
Id = "P1", Name = "Test"
Child Table
ChildId = 1, Id="P1", Name = "N1", Value = "V1"
ChildId = 2, Id="P1",Name = "N1", Value = "V2"
ChildId = 3, Id="P1",Name = "N2", Value = "V3"
在我的情况下,我需要部分更新孩子。 在更新的Parent中需要更新记录2 设置值ChildId = 2,值=“NEWVALUE” 和删除 ChildId = 1,Id =“P1”,Name =“N1”,Value =“V1 “ 和ChildId 3将被保留。
,所以我得到了家长从数据库首先,
var entity = _parentRepo.getById("P1");
var children = entity.Children;
var updatedChildren = children.ToList<Child>;
var tmpList = new List<Child>();
//biz means the business logic object which contains update info
if (biz.N1.Count > 0){
var existN1 = children.Where(x=>x.Name.Equals("N1")).Select(y=>y.ChildId);
int count = existN1.Count;
int index = 0;
biz.N1.ForEach(x=>{
if(index < count){
tmpList.Add(new Child(){ Id = existN1[index],Name="N1",Value="newValue",Parent = entity });
}else{
tmpList.Add(new Child(){ Name="N1",Value="newValue",Parent = entity });
}
});
updatedChildren.RemoveAll(x=>x.Name.Equals("N1"));
updateChildren.AddRange(tmpList);
}
entity.Children = updateChildren;
//Save the entity
然而,在数据库,记录2更新值设定为 “NEWVALUE”,但并没有消除childID的= 1,ID =“P1 “,名称=”N1“,值=”V1“。 为什么?
在此先感谢。
更改最后几个代码,然后生活变得轻松。 'entity.Children.Clear(); updateChildren.ForEach(x => entity.Children.Add(x)' – user1438980