System.InvalidOperationException (another entity of the same type already has the same primary key value

0
This is my Master Table
 [Key]
    public int ID { get; set; }
    [Required]
    public string Description { get; set; }
    [Display(Name = "Discontinue")]
    public bool IsDeleted { get; set; }
[Required]
    [Display(Name = "Created By")]
    public virtual ApplicationUser CreatedById { get; set; }
    //[Required]
    [Display(Name = "Created By DateTime")]
    public DateTime? CreatedByDateTime { get; set; }
    //[Required]
    [Display(Name = "Modified By")]
    public virtual ApplicationUser ModifiedById { get; set; }
    //[Required]
    [Display(Name = "Modified By Datetime")]
    public DateTime? ModifiedByDatetime { get; set; }

In my master Controller, I have a method for creating and this method will save CREATEDBYID = USERID AND ALSO CREATEDBTDATETIME

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Description,IsDeleted,CreatedByDateTime,ModifiedByDatetime")] Master master)
    {
        ModelState["CreatedById"].Errors.Clear();
        if (ModelState.IsValid)
        {
            master.CreatedById = db.Users.Find(User.Identity.GetUserId()); 
            master.CreatedByDateTime = DateTime.Now;
            db.Master.Add(master);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(master);
    }

And the second method for edit, this method will get the userId for the person who modified the record and stores it in the modifiedbyid

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ID,Description,CreatedByDateTime,CreatedById,IsDeleted")] Master master)
    {
        //var count = ViewData.ModelState.Values.Where(v => v.
        if (ModelState.IsValid)
        {
            master.ModifiedByDatetime = DateTime.Now;
            master.ModifiedById = db.Users.Find(User.Identity.GetUserId());
            db.Entry(master).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(master);
    }

In the website, I am able to change the description and is deleted field other columns are hidden but when I click on save this error shows

System.InvalidOperationException HResult=0x80131509 Message=Attaching an entity of type 'CleaningSupplies.Database.Models.ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case, use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate. Source=EntityFramework

c#
entity-framework
asp.net-mvc-5
asked on Stack Overflow May 3, 2018 by Abdulrazzaq Ali Ahmed • edited May 3, 2018 by Bablu Ahmed

1 Answer

0

When you pass in that object it creates a new object. You should query the database with the ID to get the object from database, you then save that. Otherwise you are trying to save a new object with the same key as what's already in the database and will get an error. So an example from a project I did last week is

var roomModels = await db.RoomModels.FindAsync(id);

this variable "roomModels" is the reference that can be saved back to the database. Be careful though as this means you have two objects, one which was passed into the controller and the other that you need to save back to the database.

answered on Stack Overflow May 3, 2018 by Keith

User contributions licensed under CC BY-SA 3.0