Coding⏱️ 3 min read📅 2026-06-03

How to Fix: How to add/update child entities when updating a parent entity in EF

To update a parent entity in EF with a one-to-many relationship, use the Include method to eager load the children entities and then set the Children property.

Quick Answer: Use Include to eager load children entities and update the Parent entity. For example: db.Parents.Update(parent => { parent.Children = db.Children.Where(c => c.Id == parent.Id).ToList(); });

The issue with adding or updating child entities when updating a parent entity in Entity Framework (EF) can be frustrating, especially when working with one-to-many relationships.

This problem affects developers who use EF to manage their database operations and may impact the performance of their applications.

🔍 Why This Happens

  • The primary reason for this issue is that EF does not automatically update or add child entities when updating a parent entity. This is because EF uses change tracking to detect changes, but it requires explicit updates or additions.
  • Another possible cause is the use of Code First Fluent API, which can lead to issues with navigation properties and relationships.

🚀 How to Resolve This Issue

Using the Include Method

  1. Step 1: To fix this issue, you need to include the child entities in your update action using the Include method.
  2. Step 2: For example, you can use `context.Parents.Include(p => p.Children)` to eager load the child entities before updating the parent entity.
  3. Step 3: Alternatively, you can use `context.Entry(p).Collection(c => c.Children).Load()` to lazy-load the child entities after updating the parent entity.

Using Change Tracking

  1. Step 1: Another approach is to use change tracking to detect changes in the child entities. This can be done by setting the `State` property of each child entity to ` EntityState.Modified` or ` EntityState.Added`.
  2. Step 2: For example, you can use `context.Entry(c).State = EntityState.Modified` to update a child entity that already exists in the database.

🎯 Final Words

By using the Include method or change tracking, you can resolve the issue of adding or updating child entities when updating a parent entity in EF. Remember to always eager-load or lazy-load the child entities to avoid performance issues.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions