Entity Framework throws "Collection was modified" when using observable collection
I have a class Employee, and class Company, which contains a (observable) list of employees. The observable list is derived from List<>, and basically looks like this:
public class ObservableList<T> : List<T>
{
// declaration of delegates and events here
new public virtual void Add(T item)
{
CollectionChangingEventArgs<T> e = new CollectionChangingEventArgs<T>(new T[] { item }, ObservableListChangeAction.Adding);
OnAdding(e);
if (e.CancelAction)
return;
base.Add(item);
CollectionChangedEventArgs<T> ed = new CollectionChangedEventArgs<T>(new T[] { item }, ObservableListChangeAction.Added);
OnAdded(ed);
}
}
The events are wired in Company constructor. So the whole thing looks approximately like this:
public class Employee
{
// stuff here
}
public class Company
{
// stuff
ObservableList<Employee> employees = new ObservableList<Employee>();
public ObservableList<Employee> Employees { get { return this.employees; } }
public Company()
{
Employees.Adding += new ObservableList<Employee>.CollectionChangingEventHandler(Employees_Adding);
}
void Employees_Adding(object sender, CollectionChangingEventArgs<Employee> e)
{
// do some checks.. none alter the collection
*edit*
// I have a line that does this:
**employee.Employer = this;**
//So if the employer was saved prior to this point, it errors out.
}
}
Now, if I do this:
Company c = new Company();
Employee e = new Employee();
c.Employees.Adding(e);
c.Save();
it works fine.
If, however, I save employee first, like this:
Company c = new Company();
Employee e = new Employee();
e.Save();
c.Employees.Adding(开发者_如何学Pythone);
c.Save();
then EF throws an exception: Collection was modified; enumeration operation may not execute.
Save() method comes from a base class, basically does this:
this.dbContext.Set<T>().Add(instance);
dbContext.SaveChanges();
This is a stack trace:
at System.Collections.Generic.List
at System.Data.Objects.ObjectStateManager.DetectChanges() at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force) at System.Data.Entity.Internal.Linq.InternalSet1.Enumerator.MoveNextRare() at System.Data.Objects.ObjectStateManager.PerformAdd(IList
1 entries)1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet
1.Add(Object entity) at System.Data.Entity.DbSet`1.Add(TEntity entity)
If I change ObservableList to List<> - it works. If I don't hook up events - it works. So basically EF doesn't like the events for some reason. When I'm saving the Company, they're not fired, btw.
I am confused.. Any idea what could be causing this ?
精彩评论