0

AutoMapper 7.0.1

Found an interesting issue that I couldn't explain. When mapping the view model back to the DB entity object, the Id property is not mapped and is always 0, unless I explicitly set its MapFrom in the CreateMap definition.

In the database, the TimeDetail.Id column is an auto-increment column, but I don't see how automapper would know that...but that was the only reason I could think of. Plus, this is for instances of updating an existing TimeDetail.

Debugger showing Id is populated in viewModel: enter image description here

Debugger showing entity object that was mapped from automapper with Id = 0: enter image description here

Map expression:

var entity = Mapper.Map<TimeDetail>(viewModel);

DB Table class object:

public partial class TimeDetail
{
    public int Id { get; set; }
    ....other columns
}

View Model:

public class TimeDetailsListViewModel
{
    public int Id { get; set; }
    ... other columns
}

Map:

CreateMap<TimeDetailsListViewModel, TimeDetail>(MemberList.Destination).IgnoreAllVirtual()
    .ForMember(dest => dest.Id, c => c.MapFrom(m => m.Id)) <---- Id is 0 if I don't explicitly set the map using this
    .ForMember(dest => dest.StartDateTime, c => c.MapFrom(m => TimeUtilities.ConvertToUTCDateTime(m.StartDateTime).Value))
    .ForMember(dest => dest.EndDateTime, c => c.MapFrom(m => TimeUtilities.ConvertToUTCDateTime(m.EndDateTime)))
    ;

IgnoreAllVirtual Extension Method:

public static class AutoMapperExtensions
{
    public static IMappingExpression<TSource, TDestination>IgnoreAllVirtual<TSource, TDestination>(
                this IMappingExpression<TSource, TDestination> expression)
    {
        var desType = typeof(TDestination);
        foreach (var property in desType.GetProperties().Where(p =>
                                    p.GetGetMethod().IsVirtual))
        {
            expression.ForMember(property.Name, opt => opt.Ignore());
        }

        return expression;
    }        
}
crichavin
  • 4,672
  • 10
  • 50
  • 95

1 Answers1

0

Found the answer. It had to do with false positives in my IgnoreAllVirtual extension method as was found by @Alexei answer on this post.

crichavin
  • 4,672
  • 10
  • 50
  • 95