如何更新 Entity Framework 中的实体?

How to update an entity in Entity Framework?

当我更新此实体时出现此错误:

My Class for database is different with my class in viewmodel

但我转换了它。

请帮助我并向我发送正确的代码。

谢谢

我的错误:

Attaching an entity of type 'DomainModel.Models.Tbl_Images' 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

我的代码:

public bool Update(ImagesEditVM model)
{
        bool result = false;

        try
        {
            DomainModel.Models.Tbl_Images img = new Tbl_Images
            {
                Id = model.Id,
                Code = model.Code,
                Image = model.Image,
                Language = model.Language,
                Title = model.Title
            };

            db.Tbl_Images.Attach(img);
            db.Entry<DomainModel.Models.Tbl_Images>(img).State = EntityState.Modified;
            db.SaveChanges();      

            result = true;
            return result;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
}

一种方法是先查询图像。然后更新值并显式调用 SaveChangesSaveChangesAsync.

try
{
    var updatingImage = _db.Tbl_Images.FirstOrDefault(i => i.Id == model.Id);

    if (updatingImage != null)
    {
        // either manually map those values or use auto mapper.
        updatingImage.Code = model.Code;
        updatingImage.Image = model.Image;
        updatingImage.Language = model.Language;
        updatingImage.Title = model.Title;

        _db.Tbl_Images.Update(updatingImage);
        _db.SaveChanges();
    }
    ...
}
catch (Exception ex)
{
    throw new Exception(ex.Message);
}

你可以试试这个:

    public bool Update ( ImagesEditVM model )
    {
        bool result = false;
        try
        {

            var existing = db.Tbl_Images.Find ( model.Id );
            if ( existing == null )
            {
                context.Add ( model );
            }
            else
            {
                db.Entry ( existing ).CurrentValues.SetValues ( model);
            }

            context.SaveChanges ( );


            result = true;
            return result;
        }
        catch ( Exception ex )
        {
            throw new Exception ( ex.Message );
        }
    }

看到这个Link