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