在過去的2天裏,這一直讓我瘋狂。 我有3個很基本的類(當然,減少可讀性)EF 4.1和「集合被修改;枚舉操作可能無法執行」。例外
public class Employee
{
public string Name { set; get; }
virtual public Employer Employer { set; get; }
public Employee(string name)
{
this.Name = name;
}
}
,
// this basically ties Employee and his role in a company.
public class EmployeeRole{
public int Id { set; get; }
virtual public Employee Employee { set; get; }
public string Role { set; get; }
public EmployeeRole(Employee employee, string role){
this.Employee = employee;
this.Role = role;
}
}
和
public class Employer{
public string Name { set; get; }
List<EmployeeRole> employees = new List<EmployeeRole>();
virtual public List<EmployeeRole> Employees { get { return this.employees; } }
public Employer(string name, Employee creator){
this.Name = name;
this.Employees.Add(new EmployeeRole(creator, "Creator"));
creator.Employer = this;
}
}
看起來很簡單。不對DbContext中的這些類進行任何特定的配置。
但是,當我運行下面的代碼
using (DbContext db = DbContext.GetNewDbContext()){
Employee creator = new Employee("Bob");
db.Employees.Add(creator);
db.SaveChanges();
Employer employer = new Employer("employer", creator);
db.Employers.Add(employer);
db.SaveChanges();
// I know I can call SaveChanges once (and it actually works in this case),
// but I want to make sure this would work with saved entities.
}
它拋出異常如下:
集合被修改;枚舉操作可能不會執行。
堆棧跟蹤:
在System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource 資源)維持在 System.Data.Objects System.Collections.Generic.List
1.Enumerator.MoveNextRare() at System.Collections.Generic.List
1.Enumerator.MoveNext() .ObjectStateManager.PerformAdd(IList entries)at System.Data.Objects.ObjectStateManager.DetectChanges() at System.Data.Objects.ObjectContext.DetectChanges()at System.Data.Entity.Internal.InternalContext.Dete ctChanges(布爾 力)在 System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet
1.增加(對象實體)
在System.Data.Entity.DbSet`1.Add(TEntity實體)
任何人有一個想法是怎麼回事,也許如何解決它? 謝謝!
您在'僱主'級擁有'僱員'屬性和'列表<僱員角色'!沒有其他信息,他們不能映射到一起。請在這裏留下完整的代碼或更多解釋您的目的。或者你可以在這裏上傳數據庫模式的屏幕截圖嗎? –
http://social.msdn.microsoft.com/Forums/en-US/1a49f75d-5168-4829-95f8-02eae38a3ee3/entityframework-41-exception-collection-was-modified-enumeration-operation-may-not-execute – Mohsen