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
Masterentity query used in GET method? It is possible that you're queryingMasterentity in GET method and then forgot to useEntityState.Detached,AsNoTracking()or simply re-attach the entity before saving. - Tetsuya Yamamoto