mad*_*nic 25 c# entity-framework
我目前正在使用EF 4.0.我的目标是删除子集合并将新的集合添加到同一父集合.
public void AddKids(int parentId, Kids newKids)
{
using (ModelContainer context = new ModelContainer(connectionString))
{
using (TransactionScope scope = new TransactionScope())
{
var query = from Parent _parent in context.Parents
where _parent.ParentId == parentId select _parent;
Parent parent = query.Single();
while (parent.Kids.Any())
{
context.Kids.DeleteObject(parent.Kids.First());
}
if (newKids != null)
{
foreach (Kid _kid in newKids)
{
parent.Kids.Add(new Kid
{
Age = _kid.Age,
Height = _kid.Height
});
}
}
scope.Complete();
}
context.SaveChanges(); //Error happens here
}
}
Run Code Online (Sandbox Code Playgroud)
错误来自标题:收集被修改; 枚举操作可能无法执行.
任何帮助,将不胜感激.
Sco*_*iAS 46
您看到了这一点,因为您从当前具有活动操作的集合中删除了对象.更具体地说,您正在更新Kids集合,然后在while循环中对其执行Any()运算符.使用IEnumerable实例时,这不是受支持的操作.我建议你做的是重写你的时间:
parent.Kids.ToList().ForEach(r => context.Kids.DeleteObject(r));
Run Code Online (Sandbox Code Playgroud)
我希望有所帮助.
| 归档时间: |
|
| 查看次数: |
19496 次 |
| 最近记录: |