fbpx

Error: “The EntityCollection could not be initialized…”

Overlapping colored triangles

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.

About the Author:

Visionfriendly.com

Visionfriendly.com

VisionFriendly.com has been building successful websites for over 20 years and covers all areas of website design, development and marketing with creative custom web designs and a robust in-house team of programmers to get your web marketing to work exactly the way you need it to.

Share On:

Share on facebook
Share on twitter
Share on linkedin

Comments:

Leave a Comment

Your email address will not be published. Required fields are marked *

Copyright © 2021, All Rights Reserved
Tri Colored Triangles
Scroll to Top

Take your business to the

Next Level!

Visionfriendly.com has the right team to make your business stand out from other professional websites.

Ready For Takeoff?

A Completely Customized
Digital Marketing Experience

We'll be in touch within one business day to discuss your goals and create a personalized plan that fits both you and your business.

Let’s start a Conversation