If you are getting this InvalidOperationExcepton from Entity Framework:
The EntityCollection could not be initialized because the relationship manager for the object to which the EntityCollection belongs is already attached to an ObjectContext. The InitializeRelatedCollection method should only be called to initialize a new EntityCollection during deserialization of an object graph.
It's likely because you are trying to directly set an EntityCollection of an existing Entity to an EntityCollection that you created instead of using EntityCollection.Add(). For example, this code gets an existing contact, Mr. Smith, from the database and tries to replace his addresses:
using (var context = new MyEntities())
{
Contact mrSmith = (from c
in context.Contacts
where c.LastName == "Smith"
select c).First();
EntityCollection<Address> addresses = new EntityCollection<Address>();
Address addy1 = new Address();
addy1.Street1 = "123 Main";
addy1.City = "New York";
// etc
Address addy2 = new Address();
addy2.Street1 = "987 Elm";
addy2.City = "Chicago";
// etc
addresses.Add(addy1);
addresses.Add(addy2);
mrSmith.Addresses = addresses;
context.SaveChanges();
}
Lines 8 and 20-23 are the problem. The correct usage is:
using (var context = new MyEntities())
{
Contact mrSmith = (from c
in context.Contacts
where c.LastName == "Smith"
select c).First();
Address addy1 = new Address();
addy1.Street1 = "123 Main";
addy1.City = "New York";
// etc
Address addy2 = new Address();
addy2.Street1 = "987 Elm";
addy2.City = "Chicago";
// etc
foreach (var a in mrSmith.Addresses.ToList())
{
context.DeleteObject(a);
}
mrSmith.Addresses.Add(addy1);
mrSmith.Addresses.Add(addy2);
context.SaveChanges();
}
Interestingly enough, this only applies to Updates. With Inserts, either method works fine.