AutoMapper not automatically copying Id column of same name

automapper automapper-6 c# entity-framework-6

Question

70.1 AutoMapper

I came into a fascinating problem that I couldn't explain. The Id attribute is never mapped and is always set to 0 when mapping the view model back to the DB entity object unless I specifically specify its MapFrom in theCreateMap definition.

The data base contains theTimeDetail.Id Although I don't see how automapper would know that it is an auto-increment column, that was the only explanation I could come up with. Additionally, this is used when modifying an existing TimeDetail.

Debugger active Id is filled up in the viewModel as enter image description here

Debugger displaying entity object enter image description here, which was mapped from automapper with Id = 0.

Expression on a map:

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

Object of the DB Table class:

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

Watch 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)))
    ;

Method: IgnoreAllVirtual Extension

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;
    }        
}
1
0
10/30/2018 10:27:54 PM

Popular Answer

ZZZ_tmp
0
10/30/2018 10:58:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow