Binding an object to a context fails because it already exists

I am using Unity of Work and the general CodeCamper repository.

to update an object, the general repo has:

    public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {
            DbSet.Attach(entity);
        }  
        dbEntityEntry.State = EntityState.Modified;
    }

web api method:

    public HttpResponseMessage Put(MyEditModel editModel)
    {
        var model = editModel.MapToMyEntity();
        _myManager.Update(model);
        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }

Update method:

    public void Update(MyEntity model)
    {
        Uow.MyEntities.Update(model);
        Uow.Commit();
    }

In Unityof Work:

IRepository<MyEntity> MyEntities { get; }

When updating the object, I get the following error:

: "X" , .      "" " " "", .      , .      "" "" , " " "" .

  • , , . ( .)

  • , . (, X, DTO, , -api, X .)

, ? CRUD, get .

+4
2

attach:

public void Attach<E>(ref E entity)
{
    if (entity == null)
    {
        return;
    }

    try
    {
        ObjectStateEntry entry;
        bool attach = false;
        if (ObjectStateManager.TryGetObjectStateEntry(CreateEntityKey(entitySetName, entity), out entry))
        {
            attach = entry.State == EntityState.Detached;

            E existingEntityInCache = (E)entry.Entity;
            if (!existingEntityInCache.Equals(entity))
            {
                existingEntityInCache.SetAllPropertiesFromEntity(entity);
            }
            entity = existingEntityInCache;
        }
        else
        {
            attach = true;
        }
        if (attach)
            objectContext.AttachTo(entitySetName, entity);
    }
    catch (Exception ex)
    {
        throw new Exception("...");
    }
}
+2

. . 1. , contex2 ( ). .

Pls :

1: read entity1 2 DB

context2: 2 . 1 ( 2 1).

1 2 2, throw, 2 2.

.

0

Source: https://habr.com/ru/post/1548191/


All Articles