简体   繁体   中英

Entity Framework database changes not seen in the DbContext

I have a simple application that is connected to a database (Entity Framework, code first). I have a screen that is used to update an entry to the database. I am able to update the database with the following code:

public void UpdatePlayer()
{
    Player playerInDb = GetPlayerFromDb(_player.Id);

    playerInDb.Name = Name;
    playerInDb.Score = Score;

    _context.SaveChanges();
    TryClose();
}

private Player GetPlayerFromDb(int id)
{
    return _context.Players.Single(p => p.Id == id);
}

If I refresh the database immediately after calling SaveChanges, I can see the changes in the actual database, but if I look at _context.Players, the old values are still there. It is only after I close my app and reopen it that the changes appear in the DbContext. How can I make sure the updated data from the database appears on my DbContext after calling SaveChanges?

UPDATE:

I've changed my code to the following:

    public void UpdatePlayer()
    {
        Player playerInDb = GetPlayerFromDb(_player.Id);

        playerInDb.Name = Name;
        playerInDb.Score = Score;

        using (var context = new ApplicationDbContext())
        {
            context.Players.Attach(playerInDb);
            context.Entry(playerInDb).State = EntityState.Modified;
            context.SaveChanges();
        }
        TryClose();
    }

I still have the same issue. The record is updated in the db but not in the application, so my UI does not get updated with the new data. Even if I reload the entire collection of players from the db, nothing gets updated until I completely relaunch the application.

You will need an extra step to modify the object:

_context.Players.Attach(playerInDb);

var entry = _context.Entry(playerInDb);
entry.State = EntityState.Modified;

_context.SaveChanges();   

Also you may need to check these for more details:
- https://msdn.microsoft.com/en-us/library/jj592676(v=vs.113).aspx
- Entity Framework 5 Updating a Record
- How to update record using Entity Framework 6?

Entity by itself has a mechanism to cache the entities to increase the speed time when select etc are done twice or more than one time. You can change the state of an entity by setting.

entity.State = EntityState.Modified;

Please consider using unit of work concept rather than sharing the same dbContext inside the class. This will dispose the context itself by using this syntax:

using(DbContext dbContext = new DbContext())
{
    //Do some stuff, update, delete etc
}

If you don`t dispose the context properly you end up causing other problems for application as well.

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