The entity cannot be modified using the Entity framework
I used Entity Framework in my Web Api application like this:
[HttpPut]
public System.Web.Mvc.JsonResult UpdateAccount(CollaborateurModel item)
{
if (ModelState.IsValid)
{
ApplicationUser user = UserManager.FindByIdAsync(item.id_user_fk).Result;
user.Roles.Clear();
UserManager.AddToRoleAsync(item.id_user_fk, item.Role);
ajt_collaborator entity = Mapper.Map<CollaborateurModel, ajt_collaborator>(item);
repo.UpdateCollaborateur(entity);
return new System.Web.Mvc.JsonResult { Data = true };
}
else
{
return new System.Web.Mvc.JsonResult { Data = false };
}
}
In BLL
public void UpdateCollaborateur( ajt_collaborator collaborateur)
{
if (cruder == null) cruder = new Crud<ajt_collaborator>();
cruder.Update(collaborateur);
}
In DAL
public bool Update(params T[] items)
{
if (context == null) context = GetContext();
try
{
foreach (T item in items)
{
context.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
context.SaveChanges();
return true;
}
catch
{
return false;
}
}
The method Update
throws an exception
Could not add object type 'sport.DAL.Entities.ajt_collaborator' because another object of the same type already has this primary key value. This can happen if you use the Attach method or set the value of No Changes or Modified to the state of an object, regardless of whether the key values of the object's graphics are in conflict. Some objects may be new and may not have received any key values generated by the database. In this case, use the Add or Added method to draw the graph and set the value to No Changes or Modified for state objects other than new objects.
I need to know
- What is the reason for this exception?
- How can I fix this?
source to share
Do not fill ajt_collaborator entity
as shown below -
ajt_collaborator entity = Mapper.Map<CollaborateurModel, ajt_collaborator>(item);
Instead, fill ajt_collaborator entity
with Find
(or Where
, etc. so that there is no new object, but we can get an existing object that was already present in the objects) and then display all properties from item
to entity
with Automapper
. Finally, use the mapping object for update purposes.
source to share
-
EF thinks the context and database are out of sync because you mark an item as modified, but it doesn't have a value for its primary key.
-
A typical example for this is checking the PK field and setting the object state accordingly:
context.Entry(item).State = (item.PK == default(int)) ? System.Data.Entity.EntityState.Added : System.Data.Entity.EntityState.Modified;
(where default (int) is your PC data type)
In your case, the problem can most likely be resolved by making sure that the PK / key field is even sent to this method, so it doesn't go missing when automatically deleting or reassigning an item from the DB before calling the update method.
source to share