如何在Entity Framework中更新数据库中的记录?

时间:2016-11-04 11:30:07

标签: c# entity-framework

我正在使用带有EF的c#mvc并且我正在建立一个网站。当我使用新值更新表时,会出现以下错误。

  

{"违反PRIMARY KEY约束' PK_Table_1_1'。无法在对象' dbo.User'中插入重复的密钥。重复键值为(shan@gmail.com)。\ r \ n语句已终止。"}

这是我对桌子的设计。

enter image description here

这是我的控制器文件

[HttpPost]
    public ActionResult Manage(ManageViewModel manageviewmodel)
    {
        TheFoodyContext db = new TheFoodyContext();
        string UserEmail = Session["UserEmail"].ToString();
        User user_to_update = db.Users.Find(UserEmail);

        if (ModelState.IsValid)
        {

            try
            {
                HttpPostedFileBase photo = Request.Files["photo"];

            if (photo != null && photo.ContentLength > 0)
            {
                var path = "";
                var fileName = Path.GetFileName(photo.FileName);
                var extension = Path.GetExtension(photo.FileName);
                var allowedExtensions = new[] {".Jpg", ".png", ".jpg", "jpeg"};
                if (allowedExtensions.Contains(extension))
                {
                    string name = Path.GetFileNameWithoutExtension(fileName);
                    string myfile = name + "_" + UserEmail + extension;
                    path= Path.Combine(Server.MapPath("~/Img"), myfile);
                    photo.SaveAs(path);
                    user_to_update.photo = myfile;

                }
                else
                {
                    ViewBag.message = "Please choose only Image file";
                }


                user_to_update.email = UserEmail;
                user_to_update.fname = manageviewmodel.FirstName;
                user_to_update.lname = manageviewmodel.LastName;
                user_to_update.phone = manageviewmodel.Phone;
                user_to_update.address = manageviewmodel.Address;
                user_to_update.city = manageviewmodel.City;
                user_to_update.postcode = Convert.ToDecimal(manageviewmodel.PostCode);
                user_to_update.district = manageviewmodel.District;
                user_to_update.user_type = manageviewmodel.UserType;
                user_to_update.status = manageviewmodel.Status;
                user_to_update.photo = path;

                db.Users.Add(user_to_update);
                db.SaveChanges();

                Session["UserEmail"] = UserEmail;
                Session["FirstName"] = manageviewmodel.FirstName;
                Session["LastName"] = manageviewmodel.LastName;
                Session["Address"] = manageviewmodel.Address;
                Session["City"] = manageviewmodel.City;
                Session["PostCode"] = manageviewmodel.PostCode;
                Session["District"] = manageviewmodel.District;
                Session["UserType"] = manageviewmodel.UserType;
                Session["Status"] = manageviewmodel.Status;
                Session["Phone"] = manageviewmodel.Phone;
                return RedirectToAction("Manage");
            }
            }
            catch (Exception ex)
            {
             return View(ex.Message);
            }
            return View(manageviewmodel);
            }

            return View(manageviewmodel);

        }

这是我的模型文件

public class ManageViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string photo { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public int PostCode { get; set; }
    public string District { get; set; }
    public string UserType { get; set; }
    public string Status { get; set; }
}

1 个答案:

答案 0 :(得分:5)

您不需要再次添加用户(它已经存在且EF跟踪更改),只需致电SaveChanges即可完成。
只需删除此行:

db.Users.Add(user_to_update);

它应该有效(除非有更多错误)。