Это сводило меня с ума последние два дня. У меня есть 3 довольно простых класса (ну, сокращенные для удобства чтения)
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.Collections.Generic.List
1.Enumerator.MoveNextRare () в {{ 1}} System.Collections.Generic.List
1.Enumerator.MoveNext () в System.Data.Objects.ObjectStateManager.PerformAdd (IList1 записей)
1 ) в System.Data.Objects.ObjectStateManager.DetectChanges () в System.Data .Objects.ObjectContext.DetectChanges () в System.Data.Entity.Internal.InternalContext.DetectChanges (логическое значение ) в System.Data.Entity.Internal.Linq. InternalSet
{{1} } в System.Data.Objects.ObjectStateManager.AlignChangesInRelationships (записи IList1.ActOnSet (действие действия, EntityState newState, объектная сущность, String methodName) в System.Data.Entity.Internal.Linq.InternalSet
1.Add (Object entity)
в System.Data.Entity.DbSet`1.Добавить (TEntity entity)
Кто-нибудь знает, что происходит, и, может быть, как это исправить? Спасибо!