Entity Framework Core Interview Question #20

What is the difference between Add, Attach, and Update in EF Core?

EF Core Fundamentals & DbContext Junior Beginner

Quick Interview Answer

Add begins tracking an entity as Added, so EF Core normally inserts it when SaveChanges is called.

Detailed Explanation

Add begins tracking an entity as Added, so EF Core normally inserts it when SaveChanges is called.

Attach begins tracking an existing entity as Unchanged. It is useful when the application knows the entity already exists and wants to establish tracking without marking every property as modified.

Update generally marks an existing entity, and reachable entities as appropriate, for modification. In disconnected web applications, blindly calling Update on client-supplied entity graphs can update more columns or entities than intended, so targeted updates are often safer.

Code Example

// New entity
db.Products.Add(newProduct);

// Existing entity, initially unchanged
db.Products.Attach(existingProduct);

// Marks entity for update
db.Products.Update(modifiedProduct);

await db.SaveChangesAsync();