How do I stop Entity Framework from trying to save/insert child objects?

c# entity-framework


When I save an entity with entity framework, I naturally assumed it would only try to save the specified entity. However, it is also trying to save that entity's child entities. This is causing all sorts of integrity problems. How do I force EF to only save the entity I want to save and therefore ignore all child objects?

If I manually set the properties to null, I get an error "The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable." This is extremely counter-productive since I set the child object to null specifically so EF would leave it alone.

Why don't I want to save/insert the child objects?

Since this is being discussed back and forth in the comments, I'll give some justification of why I want my child objects left alone.

In the application I'm building, the EF object model is not being loaded from the database but used as data objects which I'm populating while parsing a flat file. In the case of the child objects, many of these refer to lookup tables defining various properties of the parent table. For example, the geographic location of the primary entity.

Since I've populated these objects myself, EF assumes these are new objects and need to be inserted along with the parent object. However, these definitions already exist and I don't want to create duplicates in the database. I only use the EF object to do a lookup and populate the foreign key in my main table entity.

Even with the child objects that are real data, I needs to save the parent first and get a primary key or EF just seems to make a mess of things. Hope this gives some explanation.

8/22/2014 7:25:06 AM

Popular Answer

As far as I know, you have two options.

Option 1)

Null all the child objects, this will ensure EF not to add anything. It will also not delete anything from your database.

Option 2)

Set the child objects as detached from the context using the following code

 context.Entry(yourObject).State = EntityState.Detached

Note that you can not detach a List/Collection. You will have to loop over your list and detach each item in your list like so

foreach (var item in properties)
     db.Entry(item).State = EntityState.Detached;
8/22/2014 8:47:37 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow