Warm tip: This article is reproduced from serverfault.com, please click

Entity not updating in database using Entity Framework 6

发布于 2020-11-28 15:34:46

I am creating an API for my Xamarin Android application and I have created this method to update password in the database:

[HttpPut]
[ActionName("updatepassword")]
public HttpResponseMessage updatepassword(string password,string email)
{
    user_table user = dbe.user_table
                         .Where(x => x.email_address == email)
                         .FirstOrDefault();
    user.password_hash = password.GetHashCode();

    var response = dbe.SaveChanges();
    string finalresponse = "password updated successfully" + response;

    return Request.CreateResponse(HttpStatusCode.OK, finalresponse );
}

But when I test it using postman it shows that 0 entities have been affected.

I also tried using

dbe.user_table.AddorUpdate()

but it doesn't work either, please help me.

This is my postman query

http://192.168.10.9:8044/api/account/updatepassword/?password=asad1234&email=asadregards@gmail.com

I have published my API on IIS Server that is why I am using IP Address instead of localhost.

Questioner
Asad Ullah
Viewed
0
Sergey 2020-11-30 22:26:08

Change your code to this:

var user = dbe.user_table
            .Where(x => x.email_address == email)
             .FirstOrDefault();

var response=0;
if (user!=null)
{
   user.password_hash = password.GetHashCode();
 dbe.Entry(user).State = EntityState.Modified;

// Or you can try 
//dbe.Entry(user).Property(i => i.password_hash).IsModified = true;

    response = dbe.SaveChanges();
}
 
........
........

And maybe it's a good idea to change you API header too:

[Route("updatepassword/{password}/{email}")]
public  IHttpActionResult updatepassword(string password,string email)
{
.........
.......
return response>0 ? Ok():BadRequest();

}