Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Entity failed to be modified with 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;
            }
        }

An exception is thrown in the Update method

Failed attaching a type of entity "sport.DAL.Entities.ajt_collaborator " because another entity of the same type already has this primary key value . This can occur when you use the "Attach " method or set the " Unchanged " value or "Modified" to the state of an entity, whether entities graphic feature key values ​​in conflict. Some entities may be new and may have not received any key values ​​generated by the database . In this case , use the "Add" method or the " Added " entity to draw the graph and assign the value " Unchanged " or " Modified" to the state entities other than the new entities .

I need to know

  1. What is the reason of this exception?
  2. How can I fix it?

Upvotes: 3

Views: 623

Answers (3)

ramiramilu
ramiramilu

Reputation: 17182

Do not populate ajt_collaborator entity as shown below -

ajt_collaborator entity = Mapper.Map<CollaborateurModel, ajt_collaborator>(item);

Instead Populate ajt_collaborator entity using Find (or Where etc., so that there will not be a new object, but we can get the existing object which was already present in entities), then map all the properties from item to entity using Automapper. Finally use the mapped entity for update purpose.

Upvotes: 2

Brad C
Brad C

Reputation: 2982

  1. EF thinks that the context and the database are out of sync because you are marking an item as modified but it doesnt have a value set for its primary key.

  2. The typical pattern for handling this is to check the PK field and set the entity state accordingly:

context.Entry(item).State = (item.PK == default(int)) ? System.Data.Entity.EntityState.Added : System.Data.Entity.EntityState.Modified;

(where default(int) is the datatype of your PK)

In your case, the problem can be solved most likely by making sure the PK / key field is even being sent to that method so it is not missing when being automapped or by refetching the item from the DB before calling your Update method.

Upvotes: 1

floatas
floatas

Reputation: 170

It also might be that your item is received without primary key, or primary key might be lost after mapping.

Upvotes: 1

Related Questions