I get an error in my project.

   [HttpPost]
    protected virtual ActionResult Update(T entity)
    {
        var success = true;
        var errorMessages = new List<ErrorMessage>();
        try
        {
            var originalEntity = _genericService.Find(entity.Id);

            SetNullToTransientReferences(entity);
            if (!errorMessages.Any())
            {
                _genericService.Update(entity);
                //AfterUpdate(entity, originalEntity);
            }
            else
            {
                success = false;
            }

        }
        catch (Exception ex)
        {
            success = false;
            //errorMessages.AddRange(ExceptionService.GetErrorMessages(ex));
        }
        ResolveCircularReferences(entity);
        return Json(new
        {
            Data = entity,
            Success = success,
            Errors = errorMessages,
        }, JsonRequestBehavior.AllowGet);
    }

Generic Repository Update Method

  public virtual void Update(TEntity entityToUpdate)
    {
        _context.Entry(entityToUpdate).State = EntityState.Modified;
    }

First, I urge model then I'm doing, but I get an error correction process.

Thanks in advance

2

There are 2 answers

0
amcdermott On

This happens when you perform an action that would lead to the EF context monitoring two instances of the same entity.

For example, say EF is already aware of a Customer entity with CustomerId = 8. Now, if you perform some action that would in effect say to EF, "here's a Customer, the CustomerId is 8 - I want you to track it for me", EF can't do that for you.

1
Shane On

t seems that entity you are trying to modify is not being tracked correctly and therefore is not recognized as edited, but added instead.

Instead of directly setting state,you could try detaching and re-attaching:

//_context.Entry(entityToUpdate).State = EntityState.Modified;

    _context.Entry(entityToUpdate).State = EntityState.Detached;
    _context.entityToUpdate.Attach(entityToUpdate);