Questo mi ha fatto impazzire per gli ultimi 2 giorni. Ho 3 classi abbastanza di base (beh, ridotto per migliorare la leggibilità)EF 4.1 e "La raccolta è stata modificata, l'operazione di enumerazione potrebbe non essere eseguita." eccezione
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;
}
}
e
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;
}
}
sembra abbastanza semplice. Non si esegue alcuna configurazione specifica per tali classi in DbContext.
Ma, quando ho eseguito seguente codice
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.
}
getta seguente eccezione:
Collection è stato modificato; l'operazione di enumerazione potrebbe non essere eseguita.
traccia stack:
a System.ThrowHelper.ThrowInvalidOperationException (ExceptionResource risorse) a System.Collections.Generic.List
1.Enumerator.MoveNextRare() at System.Collections.Generic.List
1.Enumerator.MoveNext() in System.Data.Objects .ObjectStateManager.PerformAdd (IList iscrizioni) a System.Data.Objects.ObjectStateManager.DetectChanges() a System.Data.Objects.ObjectContext.DetectChanges() a System.Data.Entity.Internal.InternalContext.Dete ctChanges (booleano vigore) System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet
1.Add (entità Object)
a System.Data.Entity.DbSet`1.Add (entità TEntity)
Qualcuno ha un'idea di cosa sta succedendo e forse come risolverlo? Grazie!
Si ha la proprietà 'Datore di lavoro' su 'Dipendente' e' Elenco 'sulla classe' Datore di lavoro'! Non possono mappare insieme senza ulteriori informazioni. Per favore lascia qui il codice completo o più spieghi il tuo scopo. Oppure puoi caricare uno screenshot dello schema del database qui per favore? –
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