I'm using Automapper 12 to map a model over an existing EF entity. Ignores are respected on the main entity being updated, but not on the related entities and I'm not quite sure why (lacking proper collections support?)
var model = new User() {
UserId = 1,
Name = "Joe",
Tickets = new List<Ticket>() {
TicketId = 1,
Title = "Test Ticket",
}
};
var entity = await context.User.Include(x => x.Tickets).Where(x => x.UserId == userId).FirstOrDefaultAsync();
entity = _mapper.Map(model, entity);
await context.SaveChangesAsync();
// mapping profile
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<DataModel.User, ApiModel.User>()
.ForMember(x => x.Name, options => options.MapFrom(x => x.Name))
.ForMember(x => x.Tickets, options => options.MapFrom(x => x.Tickets))
.ForMember(x => x.UserId, options => options.Ignore());
CreateMap<DataModel.Ticket, ApiModel.Ticket>()
.ForMember(x => x.Title, options => options.MapFrom(x => x.Title))
.ForMember(x => x.TicketId, options => options.Ignore());
}
}
Looking at the above, one would expect the UserId doesn't get clobbered, and neither does the TicketId in the related entity. But what actually happens is UserId doesn't get modified, but the Ticket objects are created as new objects rather than mapping over the existing one thus giving TicketId = 0.
What's the recommended approach? Map all the related values separately?