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