Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 41 ยท Change Tracking and Saving

Add, Update, Remove and Disconnected Entities

Learn EF Core Add, Update, Remove, Attach and Find, why Update overwrites every column, how to save disconnected entities from web requests safely, and the patch pattern, with runnable stand-ins.

In the last two lessons the entity came out of the same context that saved it: a connected scenario. In web apps you often have a different situation. A user edits a form, and the server receives a plain object built from the request. No context ever saw the original; that object is disconnected. The methods you choose (Add, Update, Attach, Remove) decide what SQL runs, and a wrong choice either does nothing or silently overwrites data.

The EF Core code here is read-only. The runnable blocks are stand-ins that print the SQL a choice would produce.

The basic methods

C#
db.Products.Add(product);           // state Added      -> INSERT
db.Products.AddRange(list);         // many Added
db.Products.Remove(product);        // state Deleted    -> DELETE
db.Products.Attach(product);        // state Unchanged  -> nothing, just start tracking
db.Products.Update(product);        // state Modified   -> UPDATE of ALL columns

All of them also exist on the context (db.Add(entity)) and set the state of the whole graph reachable from the entity unless noted, so adding a blog with posts adds the posts too.

Add and keys

For an entity with a database-generated key, Add always means Added (INSERT), whatever the key value in your object is. If the key is not generated (you assigned a Guid or a natural key), Add is still Added; use Attach or Update when the row exists.

Entities with a generated key and a non-default key value are treated differently by Update: Update marks them Modified; with the default (0) key it marks them Added.

Remove

Remove needs a tracked or attached entity. To delete by key without loading the row you can attach a stub:

C#
var stub = new Product { Id = 42 };
db.Products.Remove(stub);      // Attach as Deleted
await db.SaveChangesAsync();   // DELETE FROM Products WHERE Id = 42, one round trip

For set-based deletes see bulk operations.

Find: look in the tracker first

C#
var p = await db.Products.FindAsync(42);   // tracker first, then the database

Find looks for the key in the identity map and only queries when needed. It is the right call for "get by primary key" when you might already have it tracked. It does not support Include; for that use FirstOrDefaultAsync.

The danger: Update overwrites everything

Suppose a form posts { Id: 1, Name: "Pen", Price: 2.5 } and your entity also has Stock, CreatedAt and a Cost that the form does not carry. The deserialized object has defaults for them (0, DateTime.MinValue...). Now:

C#
db.Products.Update(postedProduct);
await db.SaveChangesAsync();
// UPDATE Products SET Name=@p0, Price=@p1, Stock=0, Cost=0, CreatedAt='0001-01-01' WHERE Id=1

Every column is written, including the ones the form never sent. This is the overposting/overwriting problem in disguise: data silently lost.

The stand-in prints the SQL for Update versus a tracked change:

C# Stand-in: Update versus tracked change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The safe pattern: load, then copy allowed fields

For updates from a form or API, prefer this: accept a small DTO (data transfer object) that contains only the editable fields, load the entity, copy those fields onto it, and save.

C#
public record UpdateProductDto(string Name, decimal Price);

public async Task<bool> UpdateAsync(int id, UpdateProductDto dto)
{
    var product = await db.Products.FindAsync(id);
    if (product is null) return false;

    product.Name = dto.Name;       // tracked: only changed columns are sent
    product.Price = dto.Price;

    await db.SaveChangesAsync();
    return true;
}

Advantages: one extra SELECT, but you get only the changed columns, you cannot overwrite fields the user may not edit (an IsAdmin flag, a price you control), and concurrency checks work (optimistic concurrency). With EF Core 7+ you can also do db.Entry(product).CurrentValues.SetValues(dto) to copy matching property names in one call.

Marking only some properties modified

If you must attach a stub and update chosen columns without loading:

C#
var stub = new Product { Id = 1, Price = 2.50m };
db.Attach(stub);                                   // Unchanged
db.Entry(stub).Property(p => p.Price).IsModified = true;
await db.SaveChangesAsync();                       // UPDATE Products SET Price = 2.50 WHERE Id = 1

Only Price is written. Use it for small hot paths, not as a general habit.

Add and Update walk the object graph. When a new Post references an existing Blog object, the state of that blog depends on its key:

  • generated key set (non-default) and tracked state not known: Add(post) makes the post Added and, because the blog is reachable, marks the blog Added as well, which tries to insert a duplicate.
  • the fix: attach the existing blog first, or set only the foreign key: new Post { BlogId = 1 }.
C#
var post = new Post { Heading = "Hello", BlogId = 1 };   // foreign key only: no blog object in the graph
db.Posts.Add(post);

For custom rules, db.ChangeTracker.TrackGraph(root, node => { ... }) visits each entity so you decide its state (for example, Added when the key is 0, Modified otherwise).

C# Stand-in: choosing the state from the key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Soft guidance: what to use when

Situation Use
Insert a new row Add
Edit a row you loaded Change properties, SaveChanges
Edit from a DTO Find, copy fields, SaveChanges
Update a few columns without loading Attach + IsModified or ExecuteUpdate
Delete a row by key Remove(stub) or ExecuteDelete
Reattach a whole graph from elsewhere Update or TrackGraph (carefully)

Common mistakes

  • Calling Update on an entity that is already tracked. It is unnecessary and marks all columns modified.
  • Passing request objects straight to Update, overwriting fields the client never sent (and allowing overposting).
  • Adding a graph that contains existing entities without controlling their state.
  • Calling Remove on something not found (null) and getting an ArgumentNullException.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What SQL does Update(entity) generate for a disconnected entity?

    EF Core has no snapshot for a disconnected entity, so it marks every property modified.
  2. 2. Which is the safest way to apply a form post to an existing row?

    Loading and copying only allowed fields avoids overwriting data and overposting.
  3. 3. What does Find do that FirstOrDefault does not?

    Find uses the identity map first and only queries when the entity is not tracked.
  4. 4. How can you update only the Price column of an entity you did not load?

    Attach as Unchanged, then mark just that property modified.

Summary

  • Add inserts, Remove deletes, Attach starts tracking without SQL, Update marks all columns modified.
  • For disconnected data, load the entity and copy only allowed fields (a DTO) so just the changes are written.
  • Find checks the tracker first; stubs plus IsModified update chosen columns without a read.
  • Graphs need care: control the state of existing related entities.

Next: Bulk operations and raw SQL