Having error in updating my record in database my method as follows

53 views Asked by At

What I have done wrong in this code ? (I am using MVC4 and EF) As an example: Please clear this am fresher to use MVC4

EditResponse response = new EditResponse();
try
{
    using (WeMatchContext db = new WeMatchContext())
    {
        B_MEMBER_REGISTER update = new B_MEMBER_REGISTER();
        var output = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
        if(output != null )
        {
        update.FIRST_NAME = model.FIRST_NAME;
        update.LAST_NAME = model.LAST_NAME;
        update.GENDER = model.GENDER;
        update.DOB = model.DOB;

        int resultcount = db.SaveChanges();                    
        if (resultcount > 0)
        {
            response.MEMBER_ID = update.MEMBER_ID;
            response.ResultCode = 0;
            response.Message = "Updated Successfully";

        }                 
1

There are 1 answers

0
Razack On BEST ANSWER

You have to attach updated data with the db entity. please try this,

using (WeMatchContext db = new WeMatchContext())
{        
    var update = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
    if(update != null )
    {
        update.FIRST_NAME = model.FIRST_NAME;
        update.LAST_NAME = model.LAST_NAME;
        update.GENDER = model.GENDER;
        update.DOB = model.DOB; 

        //below line of code is very important. 
        db.B_MEMBER_REGISTER.Attach(update);
        db.Entry(update).State = EntityState.Modified;

        int resultcount = db.SaveChanges();                    
        if (resultcount > 0)
        {
             response.MEMBER_ID = update.MEMBER_ID;
             response.ResultCode = 0;
             response.Message = "Updated Successfully";    
        }
   }
}