2014-04-04 101 views
0

当我使用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“。 为什么?

在此先感谢。

+0

更改最后几个代码,然后生活变得轻松。 'entity.Children.Clear(); updateChildren.ForEach(x => entity.Children.Add(x)' – user1438980

回答

1

发生了什么,就是上面的代码已经打破了会话原理,拆分了链。无论何时我们希望NHibernate做出明智的决定,我们都必须始终关注底层的东西。这是不是按照:

var children = entity.Children; 
var updatedChildren = children.ToList<Child>; // a brand new NHibernate-detached coll 
... 
// operations out of the scope of the NHiberante session 
... 
entity.Children = updateChildren; // broken chain of information 

幕后,NHibernates会将自己的智能采集到entity.Children财产。据跟踪有关的变化信息(删除的元素,改变了..)所以如果被要求保存变更... NHibernate的知道...

如果我们把全新的,互不相关,NHibernate的很难找出,有一些元素缺失。没办法如何发行DELETE。

解决方案:一直使用entity.Children参考。然后我们会得到我们需要的...

+0

很酷,非常感谢。现在我改变了代码,并且它可以正常工作,谢谢100万。 – user1438980

+0

很棒的看看。 –

相关问题