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


1 answer


Problem solved! The same objects are added to Clients. I create a new contacts and events object and add to Clients.



+2


source







All Articles