I am trying to update two tables Situation
and SituationCategory
, but it is not updating as mentioned in below code and image.
public async Task<bool> UpdateSituation(int id, SituationsDto data)
{
Situations result = _mapper.Map<SituationsDto, Situations>(data);
result.Deleted = true;
_context.Entry(result).State = EntityState.Modified;
await _context.SaveChangesAsync();
SituationCategories situationCategory = new SituationCategories();
if (result.SituationCategory != null)
{
if (situationCategory != null)
{
situationCategory.Description = result.SituationCategory.Description;
}
}
await _context.SaveChangesAsync();
}
In this screenshot, I have highlighted the data which should be updated:
Please answer
An EF context knows nothing about objects unless you attach a given object to a context, or, you initially retrieved an object from a context.
Instead of just marking the entity as modified:
_context.Entry(result).State = EntityState.Modified;
You'll need to call Update()
, which, begins tracking the entity & marks it as modified, so, when you call SaveChanges()
, changes will be written to DB:
_context.Update(result);
PS. I would only call SaveChanges()
once, in this case, at the end of your method.