Home > Blockchain >  AutoMapper sets EF Core entities to detach state
AutoMapper sets EF Core entities to detach state

Time:11-09

When I map my input model with my database entities using AutoMapper, entity states are changes to 'detached' which means, that the changes aren't saved to the database.

CreateMap<User, UserInput>().ReverseMap();

Add/Update:

[BindProperty]
public IList<UserInput> UsersInput { get; set; }

public async Task<PageResult> OnGetAsync()
{

    var users = await _dbContext.Users.ToListAsync();
    UsersInput = _mapper.Map<List<UsersInput>>(signers);

    return Page();

}

public async Task<IActionResult> OnPostAsync()
{

    var users = await _dbContext.Users.ToListAsync();

    foreach (var u in users)
    {
        Console.WriteLine(_dbContext.Entry(u).State); // => Unchanged
    }

    users = _mapper.Map(UsersInput, users);

    foreach (var u in users)
    {
        Console.WriteLine(_dbContext.Entry(u).State); // => Detached
    }

    // Save and return

    await _dbContext.SaveChangesAsync(); // => Nothing is saved because entities are Detached

    return Page();

}

Has it something to do with the way I map the data?

CodePudding user response:

As long as UsersInput has an id that corresponds to the id in the Users table, then there's no reason to load anything from the DB. Just use the EF Core UpdateRange() method:

public async Task<IActionResult> OnPostAsync()
{
    var users = _mapper.Map<List<User>>(UsersInput);
    _dbContext.Users.UpdateRange(users);
    await _dbContext.SaveChangesAsync();
    return Page();
}
  • Related