Home > Backend Development > C++ > How to Prevent Entity Framework from Saving Child Entities When Saving a Parent Entity?

How to Prevent Entity Framework from Saving Child Entities When Saving a Parent Entity?

Susan Sarandon
Release: 2025-01-02 13:20:39
Original
359 people have browsed it

How to Prevent Entity Framework from Saving Child Entities When Saving a Parent Entity?

How to Prevent Entity Framework from Saving Child Objects

When using Entity Framework, saving an entity may inadvertently attempt to save associated child entities. To rectify this and solely persist the specified entity, consider the following approaches:

Using EntityState

You can set the EntityState of the child object to Unchanged, informing Entity Framework to leave it untouched:

using (var context = new DatabaseContext())
{
    context.Set<School>().Add(newItem);
    context.Entry(newItem.City).State = EntityState.Unchanged;
    context.SaveChanges();
}
Copy after login

Utilizing Foreign Keys

A more flexible approach involves leveraging foreign keys. When defining entities, specify the foreign key property on the child entity and the corresponding primary key property on the parent entity:

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; }
}
Copy after login

During entity insertion, explicitly set the child object's foreign key property and set the parent object's navigation property to null:

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

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

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

By following these techniques, you can control the persistence of child objects, ensuring that only desired entities are saved and preventing potential integrity issues.

The above is the detailed content of How to Prevent Entity Framework from Saving Child Entities When Saving a Parent Entity?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template