DbContext.Add error, the collection has been modified; enumeration operation may fail
I'm looking for answers but I haven't found them. So when I add the second item to context.Customers
, I get an exception:
The collection has been changed; the enumeration operation cannot be performed.
Why? Any help would be much appreciated.
My code:
public class CompanyInitalizer : DropCreateDatabaseAlways<CompanyContext>
{
protected override void Seed(CompanyContext context)
{
var contacts = new List<Contact>
{
new Contact {
Vezetéknév="Nagy",
Keresztnév="Jånos",
BeosztĂĄs="alkalmazott",
Email="nagy.janos@default1.com",
TelefonszĂĄm="06361254452"
},
new Contact {
Vezetéknév="Kiss",
Keresztnév="Ferenc",
BeosztĂĄs="alkalmazott",
Email="kiss.ferenc@default1.com",
TelefonszĂĄm="06361254452"
}
};
contacts.ForEach(d => context.Contacts.Add(d));
context.SaveChanges();
var events = new List<Event>
{
new Event {
IdĆpont=DateTime.Parse("12/31/2010"),
TĂpusa="TĂĄrgyalĂĄs",
LeĂrĂĄs="Ăves költsĂ©gvetĂ©s"
},
new Event {
IdĆpont=DateTime.Parse("12/31/2010"),
TĂpusa="TĂĄrgyalĂĄs",
LeĂrĂĄs="Ăves költsĂ©gvetĂ©s"
}
};
events.ForEach(d => context.Events.Add(d));
context.SaveChanges();
var customers = new List<Customer>
{
new Customer {
Cégnév ="Default1.Kft",
IrĂĄnyĂtĂłszĂĄm= 1012,
VĂĄros="Budapest",
CĂm="Tavasz utca 54.",
Weblap="http://www.default1.com",
TelefonszĂĄm="06361254452",
Contacts= contacts,
Events=events
},
new Customer {
Cégnév ="Default2.Kft",
IrĂĄnyĂtĂłszĂĄm= 2440,
VĂĄros="SzĂĄzhalombatta",
CĂm="TĂ©l utca 34.",
Weblap="http://www.default1.com",
TelefonszĂĄm="063623254452",
Contacts=contacts,
Events=events
}
};
customers.ForEach(d => context.Customers.Add(d)); //Throw exception here!
context.SaveChanges();
}
}
+3
source to share