How to update one field of specific records using Entity Framework?

前端 未结 6 1393
别跟我提以往
别跟我提以往 2021-01-31 11:10

I want update family of a person who his name is pejman. This is my object Class:

public class Person
{
    public int Id { get; set; }
    public string FirstNa         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 11:54

    The following worked for me:

    public ActionResult ChangePassword(Account account)
    {
        try
        {
                if (ModelState.IsValid)
                {
                    db.Accounts.Attach(account);
                    db.Entry(account).Property(x => x.Password).IsModified=true;
                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
        {
            Exception raise = dbEx;
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    string message = string.Format("{0}:{1}",
                        validationErrors.Entry.Entity.ToString(),
                        validationError.ErrorMessage);
                    raise = new InvalidOperationException(message, raise);
                }
            }
            ModelState.AddModelError("", raise);
    
        } 
        return View(account);
    }
    

提交回复
热议问题