Когда я обновляю этот объект, я получаю эту ошибку:
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);
}
}

Один из способов - сначала запросить изображение. Затем обновите значения и явно вызовите SaveChanges или SaveChangesAsync.
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 );
}
}
см. это Ссылка
Я изменил db.Tbl_Images.Update (updateImage); в db.Tbl_Images.Attach (updateImage); db.Entry <DomainModel.Models.Tbl_Images> (updateImage) .State = EntityState.Modified; Работай. СПАСИБО