Question
Partial Entity Updates in Entity Framework 5 with ASP.NET MVC
Question
In an ASP.NET MVC 3 application using Entity Framework 5, how can I update only selected properties of a User record without first loading the existing record from the database?
I need an approach that:
- Lets me explicitly choose which properties are updated.
- Does not require the edit view or submitted model to include every entity property, such as a password.
- Sends a single
UPDATEcommand rather than first issuing aSELECTto load the entity.
For example, setting the entire entity to EntityState.Modified performs an update without loading the entity first, but it marks every mapped property as modified:
db.Users.Attach(updatedUser);
db.Entry(updatedUser).State = EntityState.Modified;
db.SaveChanges();
Is there a clean way to attach an entity and mark only specific properties as changed?
Short Answer
Entity Framework can perform a partial update without loading the original row first. Attach an entity containing its key and permitted new values, then mark each allowed property with IsModified = true. This produces an UPDATE statement for only those columns and helps prevent accidental changes to fields that were not submitted.
Concept
Entity Framework tracks whether an entity and each of its properties have changed. When an entity is loaded through the same DbContext, EF has original values available and can detect changes automatically.
For web applications, edit data is often posted back as a detached object: it was created by model binding and is not being tracked by the current context. EF does not know its original database values.
You have two common choices for a detached object:
- Set the whole entity state to
Modified. EF assumes every mapped property should be updated. - Attach the entity as unchanged, then explicitly mark only allowed properties as modified.
The second approach supports a partial update in one database command:
entry.Property(u => u.Email).IsModified = true;
EF then generates an UPDATE containing Email, rather than every column in Users.
This matters for both efficiency and correctness. More importantly than avoiding a read, it prevents overposting: a client should not be able to submit fields such as PasswordHash, IsAdmin, or ASPNetUserId and have them silently saved.
Mental Model
Think of an entity as a paper form with many fields.
- Loading the record first is like retrieving the existing form, comparing it with the new form, and changing the differences.
- Marking the whole entity as
Modifiedis like stamping replace every field on the form. - Attaching a small entity and marking individual properties is like submitting a change request that says: “For user 42, change only the email address and telephone number.”
The entity key identifies which form to change. IsModified tells Entity Framework exactly which fields belong in the change request.
Syntax and Examples
Create an entity with its primary key and only the values that are allowed to change. Attach it, then set IsModified for each permitted property.
var user = new User
{
UserId = input.UserId,
Email = input.Email,
Telephone = input.Telephone
};
db.Users.Attach(user);
var entry = db.Entry(user);
entry.Property(u => u.Email).IsModified = true;
entry.Property(u => u.Telephone).IsModified = true;
db.SaveChanges();
Because Attach starts the entity in the Unchanged state, only properties explicitly marked with IsModified = true are included in the update.
A safer MVC design is to use a view model rather than accepting the database entity directly:
public class EditContactViewModel
{
public int UserId { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
}
The view model documents what the form is allowed to edit. It also ensures sensitive entity properties are not part of model binding.
Step by Step Execution
Consider this partial update:
var user = new User
{
UserId = 17,
Email = "ada@example.com"
};
db.Users.Attach(user);
db.Entry(user).Property(u => u.Email).IsModified = true;
db.SaveChanges();
- A
Userobject is created in memory. It has key17and a new email address. Attachtells the context that this object represents an existing database row. At this stage, EF treats its properties as unchanged.Property(u => u.Email).IsModified = truechanges EF's tracking information. EF now knows thatEmailmust be written.SaveChanges()sends an update command similar to:
UPDATE [Users]
SET [Email] = @p0
WHERE [UserId] = @p1;
- EF does not need a prior
SELECTto create this command. Other columns, such asPasswordHash, are not included in theSETclause.
Real World Use Cases
Partial updates are useful whenever a screen or endpoint edits a narrow part of a larger entity:
- Profile contact form: update email, telephone, and display name without touching account credentials.
- Administrative status action: update only
IsActiveorApprovalStatus. - Address form: update address fields without replacing payment or identity information.
- API PATCH-like endpoint: apply a specific, validated set of changes to an existing resource.
- Background job: mark an order as processed by updating only status and completion time.
In each case, send only the fields the operation is intended to change, and explicitly define which fields may be saved.
Real Codebase Usage
In production MVC applications, developers usually combine partial updates with view models, validation, authorization, and concurrency handling.
Use an operation-specific view model
Do not bind a database entity with many writable properties when the page edits only two of them.
public class ChangeEmailViewModel
{
public int UserId { get; set; }
public string Email { get; set; }
}
Validate before attaching
if (!ModelState.IsValid)
{
return View(model);
}
Also verify that the current user is authorized to edit the target record. A valid UserId is not proof of permission.
Mark an explicit allowlist of fields
var user = new User { UserId = model.UserId, Email = model.Email };
db.Users.Attach(user);
db.Entry(user).Property(u => u.Email).IsModified = true;
This is clearer and safer than trusting every field received from a request.
Check whether a row was actually updated
SaveChanges() can succeed even if an UPDATE affects zero rows, depending on the mapping and concurrency configuration. For edits where conflicting changes matter, use a concurrency token such as a rowversion column and handle DbUpdateConcurrencyException. A read-first approach is often simpler when the edit operation needs current database data, business-rule checks, or a detailed “not found” response.
Common Mistakes
Marking the entire entity as modified
This updates every mapped writable property, including properties that were omitted from the form and therefore contain default values.
// Risky for a partial form
var user = new User { UserId = model.UserId, Email = model.Email };
db.Users.Attach(user);
db.Entry(user).State = EntityState.Modified;
For example, an absent PasswordHash could be written as null or an empty value. Mark individual properties instead.
Binding directly to a sensitive entity
public ActionResult Edit(User user)
A malicious client can add extra form fields to the HTTP request. Use a small view model, then copy only approved values to the attached entity.
Forgetting the primary key
EF needs the key to generate the WHERE clause. Ensure it is present and represents an existing row.
var user = new User { UserId = model.UserId };
Marking navigation properties as modified
Property(...) is for scalar mapped properties such as strings, numbers, dates, and booleans. Relationship changes require their own relationship or foreign-key handling. For a simple foreign-key change, mark the foreign-key scalar property, such as DepartmentId, when appropriate.
Assuming one command removes all database concerns
A single UPDATE is useful, but it does not replace authorization, validation, or concurrency control. Validate the data and ensure the current user is allowed to modify that row.
Updating a property that should be database-generated
Do not mark identity keys, computed columns, or server-generated timestamps as modified unless the mapping explicitly allows it. These values are normally controlled by the database.
Comparisons
| Approach | Loads existing row first? | Chooses updated properties? | Best fit |
|---|---|---|---|
| Load entity and assign properties manually | Yes | Yes | Complex business rules, validation based on current values, or clear readable edits |
Load entity and call CurrentValues.SetValues | Yes | Usually copies all matching supplied scalar values | Trusted complete edit models; still review which fields can be bound |
Attach and set EntityState.Modified | No | No; all mapped properties are marked | Full replacement updates when every value is intentionally supplied |
Attach and set Property(...).IsModified | No | Yes | Partial forms and focused update operations |
CurrentValues.SetValues does not inherently make a submitted model safe. If the submitted object contains a sensitive matching property, it can be copied to the tracked entity. A dedicated view model remains the clearest boundary.
Cheat Sheet
// One-command partial update in EF 5
var entity = new User
{
UserId = model.UserId,
Email = model.Email
};
db.Users.Attach(entity); // Entity starts as Unchanged
db.Entry(entity).Property(x => x.Email)
.IsModified = true; // Include only Email in UPDATE
db.SaveChanges();
Attach(entity)means “this row already exists.”- The primary key must be set.
EntityState.Modifiedmarks all mapped writable scalar properties.Property(...).IsModified = truemarks one scalar property.- Use a view model to define fields the request may change.
- Validate input and authorize the operation before saving.
- Use concurrency tokens when conflicting edits must be detected.
- Do not mark keys, computed fields, or database-generated fields as modified unless intended.
FAQ
Can Entity Framework update a record without querying it first?
Yes. Create an entity with its key and the new allowed values, attach it, mark the desired properties as modified, and call SaveChanges().
Does Attach insert a new row?
No. Attach tells EF that the entity already exists and should initially be tracked as unchanged. Calling Add is the operation used for new rows.
Why not always use EntityState.Modified?
It marks every mapped property as changed. For a partial form, missing values may overwrite database values, and clients may submit fields that should not be editable.
Does IsModified update only changed values automatically?
For a detached entity, EF cannot compare values unless it first loads original values. IsModified is an explicit instruction: update this property.
Can I update several properties with IsModified?
Yes. Call Property(...).IsModified = true once for each allowed property.
Is one database command always better than loading the row first?
No. Loading first is often appropriate when you need the current data for validation, authorization, business logic, relationship handling, or concurrency decisions.
How do I prevent password or administrator fields from being changed?
Do not include them in the edit view model, do not copy them into the attached entity, and do not mark them as modified. Also enforce authorization on the server.
Mini Project
Description
Build a focused contact-details update action for a user profile. The form is allowed to change an email address and telephone number, but it must not expose or update account fields such as a password hash or administrator flag.
Goal
Update only a user's email and telephone number with Entity Framework 5 without loading the user first.
Requirements
Requirement 1
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
Best Way to Repeat a Character in C#: Building Repeated Strings Efficiently
Learn the best way to repeat a character in C#, compare StringBuilder, string concatenation, and simpler built-in options.
C# Access Modifiers and static: public, private, protected, and Defaults
Learn how C# public, private, protected, and default access control visibility, and how static differs from instance members.