Entity Framework Core: Database operation expected to affect 1 row(s) but actually affected 0 row(s) [duplicate]

There were two errors. First, I tried to call the Update() method without specifying a DbSet:

_applicationDbContext.Update(user);

Correct way:

_applicationDbContext.Users.Update(user);

The second error was trying to update a model that without first pulling it from the database:

    public bool UpdateUser(IdentityUser model)
    {
        _applicationDbContext.Users.Update(model);
        _applicationDbContext.SaveChanges();

        return true;
    }

Nope.

I first needed to retrieve it from the database, then update it:

    public bool UpdateUser(IdentityUser model)
    {
        var user = _applicationDbContext.Users.FirstOrDefault(u => u.Id == model.Id);

        user.PhoneNumberConfirmed = model.PhoneNumberConfirmed;

        _applicationDbContext.Users.Update(user);
        _applicationDbContext.SaveChanges();

        return true;
    }

Leave a Comment