how to update entity when dbcontext changed

dping lin 0 Reputation points
2023-04-22T07:33:09.2666667+00:00

using var db = new DbContext(); var entity= new entity(); db.add(entity); db.savechanges(); entity.xxx=yyyy;
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.
726 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jami 75 Reputation points
    2023-04-22T20:49:24.8066667+00:00

    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
        db.Attach(cachedEntity);
    
        // Update the entity properties
        cachedEntity.Xxx = yyyy;
    
        // Mark the entity as modified
        db.Entry(cachedEntity).State = EntityState.Modified;
    
        // Save changes to the database
        db.SaveChanges();
    }
    

    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