JcMey3r
JcMey3r

Reputation: 181

Updating Detached Entity with Children creates Modified & Delete changes using EF Core

I have a API call that needs to update an Entity and its children using EF Core but the DB Context generates Modified and Delete changes in the change tracker thus effectively updating the child items and then deleting them.

What am I doing?

I get a DTO from the API call then I fetch the original from the database with its children

 var dbModel = Repository
            .GetQueryable()
            .Include(m => m.Children)
            .FirstOrDefault(m => m.Id == dtoModel.Id);

I then map the DTO to the original model(using auto mapper) and then I call the update method

Mapper.Map(matterTeam, matter);
await Repository.UpdateAsync(matter);

This then calls the UpdateAsync down the line.

public override async Task<TEntity> UpdateAsync(TEntity entity,  CancellationToken cancellationToken = default)
    {
        _dbContext.Attach(entity);
        var updatedEntity = _dbContext.Update(entity).Entity;
        await _dbContext.SaveChangesAsync(cancellationToken);
        return updatedEntity;
    }

I have played around with setting Entity state to modified but it will still generate Modified and Delete changes.

Upvotes: 1

Views: 201

Answers (1)

JcMey3r
JcMey3r

Reputation: 181

The issue lies with Automapper. It creates a new Collection and this is what is going wrong with EF Core.

The answer is adding Automapper Collection

Quoted from github

Adds ability to map collections to existing collections without re-creating the collection object. Will Add/Update/Delete items from a preexisting collection object based on user defined equivalency between the collection's generic item type from the source collection and the destination collection.

I installed the Nuget package, registered the config as states and updated my mapper to the following which works great

CreateMap<ModelDto, Model>()
                .EqualityComparison((m, o) => m.Id == o.Id);

Upvotes: 1

Related Questions