简体   繁体   中英

Automapper issue, seems to ignore mapping of property

I'm using Automapper version 6.2.2 and I'm having issues with mapping between two classes. Automapper is used in the project for all "mapping purposes" and works well for all cases except this one.

public class WeeklyVolume    
{    
    public DateTime Week    
}    

public class WeeklyVolumeViewModel    
{    
    public DateTime Date    
    public string Week    
}`

The mapping between the classes looks like:

CreateMap<WeeklyVolumeViewModel, WeeklyVolume>()
        .ForMember(dest => dest.Week, opt => opt.MapFrom(src => src.Date))

CreateMap<WeeklyVolume, WeeklyVolumeViewModel>()
        .ForMember(dest => dest.Week, opt => opt.Ignore())
        .ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.Week));

When this mapping is used

Mapper.Map<IList<WeeklyVolumeViewModel>, IList<WeeklyVolume>>(weeklyVolumes));

an exception is thrown:

Message: AutoMapper.AutoMapperMappingException : Error mapping types.

Mapping types:

  • System.FormatException : v. 44 (0) is not a valid value for DateTime.
  • System.FormatException : The string was not recognized as a valid
  • DateTime. There is an unknown word starting at index 0.

In the mapping, the string property Week from WeeklyVolumeviewModel is ignored. Though its value "v. 44 (0)" (formatted string with week number) still seems to be trying to get mapped to the WeeklyVolume Week property, which is what I'm guessing causes the error. All the other mappings between classes work great, but here it does not seem to function properly, or am I missing something?

All the mappings are set through using

Mapper.Initialize(cfg => cfg.Addprofile(new DummyMapperclass());

The first thing I would change is

public class WeeklyVolume    
{    
    public DateTime Week {get; set;}
}    

public class WeeklyVolumeViewModel    
{    
    public DateTime Date {get; set;}
    public string Week   {get; set;}
}

then, let's see on the field names: you have two fields with the same name, but with the different type. This may confuse Automapper. He will try to convert the fields.

You can try to change 'Week' on WeeklyVolume to 'Date' and remove all mappings 'Date' to 'Date' -> Automapper will do all things automatically.

OR You can try to change field name Week (one of these) to say, Week2.

Let me know the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM