I have this EmployeeEntity class which is part of my database context.
public class EmployeeEntity
{
public int Id { get; set; }
public string FirstName { get; set; }
//more properties
}
And I have an EmployeeModel class:
public class EmployeeModel
{
public int Id { get; set; }
public string FirstName { get; set; }
//more properties
}
When mapping from model to entity, I ignore the Id so that EF Core can generate it:
cfg.CreateMap<EmployeeModel, EmployeeEntity>().ForMember(dest => dest.Id, opt => opt.Ignore());
This is all working when I add a new employee. However, when I update an existing employee, the DbContext never saves my updates.
Here is how I am updating the database:
var employeeEntity = businessEntity.Employees
.FirstOrDefault(x => x.Id == employee.Id); // get employee
// update it using provided employee model
employeeEntity = _mapper.Map<EmployeeEntity>(employee);
await dbContext.SaveChangesAsync();
I thought this was because once AutoMapper has mapped the model to entity, EF Core stops tracking it.
But manually modifying employeeEntity state before calling SaveChangesAsync() throws an exception that an employeeentity with this id is already being tracked:
dbContext.Entry(employeeEntity).State = EntityState.Modified;
await dbContext.SaveChangesAsync();
If I manually map all properties of the model to the entity, the save works fine so it is definitely an issue with how I am using AutoMapper. How can I solve this using AutoMapper?
Thanks