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

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.


Solution 1:

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;
}

Solution 2:

Long story short: Use Foreign key and it will save your day.

Assume you have a School entity and a City entity, and this is a many-to-one relationship where a City has many Schools and a School belong to a City. And assume the Cities are already existing in the lookup table so you do NOT want them to be inserted again when inserting a new school.

Initially you might define you entities like this:

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class School
{
    public int Id { get; set; }
    public string Name { get; set; }

    [Required]
    public City City { get; set; }
}

And you might do the School insertion like this (assume you already have City property assigned to the newItem):

public School Insert(School newItem)
{
    using (var context = new DatabaseContext())
    {
        context.Set<School>().Add(newItem);
        // use the following statement so that City won't be inserted
        context.Entry(newItem.City).State = EntityState.Unchanged;
        context.SaveChanges();
        return newItem;
    }
}

The above approach may work perfectly in this case, however, I do prefer the Foreign Key approach which to me is more clear and flexible. See the updated solution below:

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class School
{
    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey("City_Id")]
    public City City { get; set; }

    [Required]
    public int City_Id { get; set; }
}

In this way, you explicitly define that the School has a foreign key City_Id and it refers to the City entity. So when it comes to the insertion of School, you can do:

    public School Insert(School newItem, int cityId)
    {
        if(cityId <= 0)
        {
            throw new Exception("City ID no provided");
        }

        newItem.City = null;
        newItem.City_Id = cityId;

        using (var context = new DatabaseContext())
        {
            context.Set<School>().Add(newItem);
            context.SaveChanges();
            return newItem;
        }
    }

In this case, you explicitly specify the City_Id of the new record and remove the City from the graph so that EF won't bother to add it to the context along with School.

Though at the first impression the Foreign key approach seems more complicated, but trust me this mentality will save you a lot of time when it comes to inserting a many-to-many relationship (imaging you have a School and Student relationship, and the Student has a City property) and so on.

Hope this is helpful to you.