Update multiple entities in Entity Framework

entity-framework entity-framework-core linq multiple-tables

Question

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:

enter image description here

Please answer

1
0
8/18/2017 6:20:51 PM

Popular 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.

0
8/18/2017 7:07:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow