how to update entity when dbcontext changed

dping lin 0 Reputation points

using var db = new DbContext(); var entity= new entity(); db.add(entity); db.savechanges();;
cache.set('entity_cache',entity); /------------ other thread---------/ using var db2= new DbContext(); var entity = cache.get('entity_cache'); --------how to update entity

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
701 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jami 75 Reputation points

    When you retrieve an entity from the cache, it may no longer be tracked by the current DbContext, so you need to attach it to the new context and mark it as modified before saving the changes. Here's an example code snippet that shows how to update the cached entity with a new DbContext:

    // Retrieve the cached entity
    var cachedEntity = cache.get('entity_cache');
    // Create a new DbContext instance
    using (var db = new DbContext())
        // Attach the cached entity to the new context
        // Update the entity properties
        cachedEntity.Xxx = yyyy;
        // Mark the entity as modified
        db.Entry(cachedEntity).State = EntityState.Modified;
        // Save changes to the database

    Note that it's important to dispose of the DbContext instance after using it to avoid memory leaks. Also, make sure to call Attach() on the context before modifying the entity, otherwise, the changes won't be tracked and saved to the database. I hope this will help.

    0 comments No comments