Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following extension method for <code>DbContext</code> is an approach which would avoid to initialize your entities with some values different to the values you want to change it to. </p> <pre><code>public static class EFExtensions { public static void MarkAsModified(this DbContext context, object entity, params string[] properties) { foreach (var property in properties) context.Entry(entity).Property(property).IsModified = true; } } </code></pre> <p>You could then use it this way:</p> <pre><code>var context = new MyEntities(); context.Configuration.ValidateOnSaveEnabled = false; var note = new Model.Note { Id = noteId }; // only key properties required to set note.Note = "Some Note"; note.SomeOtherProperty = 1234; note.AndAnotherProperty = "XYZ"; context.Notes.Attach(note); context.MarkAsModified(note, "Note", "SomeOtherProperty" , "AndAnotherProperty"); context.SaveChanges(); </code></pre> <p>Note: This only works for scalar properties, not navigation properties.</p> <p>Besides validation I could imagine that this approach is problematic for a proper concurrency checking.</p> <p><strong>Edit</strong></p> <p>According to @Adam Tuliper's comment below concurrency is likely not a problem because the concurrency check is skipped when an entity is attached manually to the context (without reading it from the database) and marked as modified to send an UPDATE command to the database. It just overwrites the lastest version in the DB. Thanks to Adam for pointing this out!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload