2013-02-20 87 views
0

我想使用實體框架和ICollection子屬性來更新數據庫數據。EF4.1更新數據與ICollection屬性的孩子

而對於INSERT情況,EF會自動保存子數據,但不適用於更新情況。

所以我做了手動更新,但我想有一種方法可以自動更新,只是我不知道。

請查看我的代碼,並給我建議

public class Parent 
{ 
    [Key] 
    public int ID {get; set;} 
    public string Name {get; set;} 

    public virtual ICollection<Child> Children{ get; set; } 
} 

public class Child 
{ 
    [Key] 
    public int ID {get; set;} 
    public int ParentID { get; set; } 
    public string Name {get; set;} 
} 

//控制方法INSERT

public void InsertTest(){ 
    //generate new Parent Data with child 
    Parent parent = new Parent() { 
     Name = "Nancy" 
    }; 

    parent.Children.Add(new Child() 
    { 
     Name = "First Son" 
    }); 

    parent.Children.Add(new Child() 
    { 
     Name = "Second Son" 
    }); 

    var parentRepository = unitofwork.parentRepository; 
    parentRepository.insert(parent); //context.Set<Parent>().Add(parent); 
    unitofwork.Save(); 
    // it save child entity well 
} 

//控制方法UPDATE

public void UpateTest() 
{ 
    //generate new Parent Data with child 
    Parent parent = new Parent() 
    { 
     ID = 1, 
     Name = "Nancy" 
    }; 

    parent.Children.Add(new Child() 
    { 
     ID = 1, 
     ParentID = 1, 
     Name = "First Son Renamed" 
    }); 

    parent.Children.Add(new Child() 
    { 
     ID = 2, 
     ParentID = 1, 
     Name = "Second Son" 
    }); 

    // add new data 
    parent.Children.Add(new Child() 
    { 
     Name = "Third Son" 
    }); 

    var parentRepository = unitofwork.parentRepository; 
    parentRepository.update(parent); //context.Set<Parent>().Attach(entityToUpdate); context.Entry(entityToUpdate).State = EntityState.Modified; 
    unitofwork.Save(); 
    // it save parent data, but it does not change any for child data 

    // *** To make work, I did like this, *** 
    // var childRepository = unitofwork.childRepository; 
    //foreach (Child c in parent.Children.ToList()) 
    //{ 
    // if (c.ID < 1) 
    // { 
    //  childRepository.update(c); 
    // } 
    // else 
    // { 
    //  childRepository.insert(c); 
    // } 
    //} 

    //unitofwork.Save(); 

    // then it works. 
} 
+0

我會說你發佈你的保存/更新方法,POCO和控制器方法不能提供任何潛在問題的足夠線索 – Didaxis 2013-02-20 22:28:25

回答

1

既然你不是活得如果直接附上所選內容並將其標記爲骯髒,則EF無法檢測到它們已經改變而沒有損失來自數據庫的原始值。

要麼從數據庫中加載孩子並向他們注入數值(特別是如果您還想刪除不再列入列表中的數據)或使用工作單元標記附加數據後選擇修改後(較少的dB但是,行動不會消除現有的兒童)。

從您的代碼我假設update()方法是標記爲實體的髒。