简体   繁体   中英

When is DbContext.Entry(enttity).State = EntityState.Modified; required?

I want to clarify when I need to set the EntityState with Entity Framework Core.

Context: code-first C# Blazor Server App, SQL Server database.

Consider:

    public async Task UpdateHelper(Helper helperx)
    {
        _context.Helpers.Update(helperx);
        _context.Entry(helperx).State = EntityState.Modified;
        await _context.SaveChangesAsync();
    }

When is the line:

    _context.Entry(helperx).State = EntityState.Modified;  

required or not required?

The simple answer: Not required in conjunction with Update .

I strongly encourage avoiding code that accepts entities from browsers.

  1. Security - the "entity" coming in is a deserialized block of JSON data. Your UI may allow the user to modify some expected data, but debugging tools and add-ons can be set up to modify all fields being passed to your server call. Code that performs an Update with that entity will trust this data implicitly and overwrite your existing data state.

  2. Performance - Using Update is effectively updating all columns on an entity whether they have changed or not. It also requires you to pass a fully complete object graph between server and client at all times to ensure that data is not blanked out when attempting to save an entity.

  3. Stale Overwrites - Data passed back from the client is only as current as it was at the time it was read. Any changes that may have been made to the data since that time will be overwritten silently. Checking things like RowVersion / Timestamp means reading the data from the DB prior to updating. You should re-read data before determining if it is safe to write.

Instead, leverage POCO view models for transmitting data between client and server. This reduces the data payload to only what is needed, and avoids performance pitfalls with serializing entity graphs. It also reduces the information given to clients which attackers can inspect to build a picture of your data schema, and ensures that only values you expect to be altered get altered. ViewModels can also contain the RowVersion to compare when the entity is reloaded to detect and handle potential change conflicts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM