Gergő Sipeki
Gergő Sipeki

Reputation: 51

DbContext.Add error,Collection was modified; enumeration operation may not execute

I'm looking for answers, but I didn't find any. So when I add second element in context.Customers, I get an Exception:

Collection was modified; enumeration operation may not execute.

Why? Any help will 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="[email protected]",
                Telefonszám="06361254452"
            },

            new Contact {
                Vezetéknév="Kiss",
                Keresztnév="Ferenc",
                Beosztás="alkalmazott",
                Email="[email protected]",
                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();           
    }
}

Upvotes: 3

Views: 1617

Answers (1)

Gergő Sipeki
Gergő Sipeki

Reputation: 51

Problem solved! Same entities added to Customers. I make new contacts and events entity and add to Customers.

Upvotes: 2

Related Questions