0

I am developing an MVC app.

When I try to updated record it showing error of DBEntityValidation exception, ( beacuse its trying to add record in DB. This is my code)

public JsonResult SavePassword(int EmpId, string Password)
    {
        try
        {


        Employee e1 = db.Employees.First(i => i.Id == EmpId);
        db.Entry(e1).State = EntityState.Modified;
        e1.Password = Password;
        db.SaveChanges();


        return Json(EmpId);

        }


        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                  eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
                }
            }
             throw;
        }


    }

In exception, it shows that validation msgs, which I have checked while adding new record. So , I think its trying to add in DB insted of updating.

user1668543
  • 199
  • 3
  • 7
  • 21
  • mind posting the actual errors? – Betty Oct 23 '12 at 07:47
  • Its giving error, so I tried several ways to solve it. I have follow lthis link http://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert – user1668543 Oct 23 '12 at 09:40
  • add a break point on the foreach and manually inspect the value of e.EntityValidationErrors and eve.Entry.State. – Betty Oct 23 '12 at 09:42
  • ya, I did it...There Are total 3 errors. All these error regarding the validations. I have make 3 fields complsory in DB and 3 Validations in applicaiton.so its treating as a new record insted of updading old one. I want to know How to update the record in EF. Whether my code is right ? – user1668543 Oct 23 '12 at 12:32
  • Your code looks fine, except you shouldn't need to set the state to modified like you are. EF detects changes and will do that automatically. The only time i've seen issues like this is when you make a field required after the fact, but there are ones with it still set to null in the database. Are these fields actually correctly set on the particular entity you are loading? – Betty Oct 23 '12 at 19:44

0 Answers0