3

I'm using c# mvc with EF and i'm building a website. When i'm updating a table with new values it gives the following error.

{"Violation of PRIMARY KEY constraint 'PK_Table_1_1'. Cannot insert duplicate key in object 'dbo.User'. The duplicate key value is ([email protected]).\r\nThe statement has been terminated."}

Here is my design of the table.

enter image description here

Here is my controller file

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

        }

Here is my Model file

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

1 Answer 1

5

You don't need to add the user again (it already exists and EF tracks changes), simply call SaveChanges and you are done.
Just remove this line:

db.Users.Add(user_to_update);

and it should work (unless there are more errors).

Sign up to request clarification or add additional context in comments.

2 Comments

Why the downvote? You can't add an entity which already exists. It would have the same key and eplain the OPs exception
@Manfred Radlwimmer Thank you so much. It worked like a charm. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.