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

标签 c# entity-framework

我将 c# mvc 与 EF 一起使用,并且正在构建一个网站。当我用新值更新表时,出现以下错误。

{"Violation of PRIMARY KEY constraint 'PK_Table_1_1'. Cannot insert duplicate key in object 'dbo.User'. The duplicate key value is (shan@gmail.com).\r\nThe statement has been terminated."}

这是我设计的表格。

enter image description here

这是我的 Controller 文件

[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; }
}

最佳答案

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

db.Users.Add(user_to_update);

它应该可以工作(除非有更多错误)。

关于c# - 如何在 Entity Framework 中更新数据库中的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40421550/

相关文章:

c# - 输入保存受约束泛型类实例的变量

c# - Sum 函数的并行 For 循环性能不佳

c# - 从大文件中检索版本信息

c# - 如何在 MVC 中将 URL 作为查询字符串参数传递

c# - 在 Linq to Entities 多列中排序

c# - 加速 linq 实体查询

c# - Entity Framework 核心错误?

c# - 在razor View中设置分页页面大小DropDownList

c# - 如何防止 Entity Framework 代码优先使用不属于模型的派生类

c# - 获取 Entity Framework 中最近插入的行的ID