I have made changes to an EntityCollection which is an object of another EntityCollection, and when I try to save those changes, I get the following error:
The EntityCollection has already been initialized. The InitializeRelatedCollection method should only be called to initialize a new EntityCollection during deserialization of an object graph.
Any ideas what I might be missing?
The following is the code I used.
public void UpdateCompanyManagement(Company newCompany)
{
Company oldCompany = entities.Companies.Where(c => c.COM_ID == newCompany.COM_ID).SingleOrDefault();
oldCompany.Managements = newCompany.Managements;
try
{
entities.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
entities.Refresh(RefreshMode.ClientWins, newCompany.Managements);
entities.SaveChanges();
}
}
I'm able to save the parent collection successfully, using the following code:
public void UpdateCompanyDetails(Company newCompany)
{
Company oldCompany = entities.Companies.Where(c => c.COM_ID == newCompany.COM_ID).SingleOrDefault();
entities.ObjectStateManager.ChangeObjectState(oldCompany.city, System.Data.EntityState.Modified);
oldCompany = newCompany;
try
{
entities.SaveChanges();
}
catch (OptimisticConcurrencyException)
{
entities.Refresh(RefreshMode.ClientWins, oldCompany);
entities.SaveChanges();
}
}