Posts

Showing posts with the label AutoMapper

AutoMapper: UseValue vs ResolveUsing vs MapFrom

I just hit a confusing mapping bug whilst using AutoMapper  to map DateTime.Now to a field in my database. Every item that was being added to the database had the same value in the "DateAdded" - to the millisecond. This was because I was using the following mapping expression: Mapper.CreateMap<SourceObject, DestObject>() .ForMember(m => m.DateAdded, o => o.UseValue(DateTime.Now)); UseValue() retrieves a value on first-run and stores it in the mapping (hence the static DateTime value that's being stored in the database), whereas ResolveUsing() resolves at run-time - which is obviously why it's called Resolve Using(). A minor oversight, but confusing nonetheless. Use ResolveUsing(s => {}) when you want to resolve a destination field from a derived value. This should be used for any DateTime mappings, and any more complicated mapping functions. Use MapFrom(s => s.MemberName) when you return an actual source object member. Use UseValue() if you...

AutoMapper 2.1 AfterMap() Fires Multiple Times

I've been writing some complex mapping for the hierarchical data on my RustyShark site (the Media entities on the site consist of a lot of dynamic meta data, which can be added and removed when edited). I'm using Entity Framework and AutoMapper, and I've ran in to an issue where AfterMap() executes multiple times, when it should only really execute once. I just thought I'd post my workaround, which also helps to demonstrate how C# interfaces can be handy. Here's what my source entity looks like: public class Medium : IAutoMapperAfterMapUsage { public int ? MediumID { get ; set ; } public string Title { get ; set ; } public DateTime ReleaseDate { get ; set ; } public User CreatedBy { get ; set ; } public DateTime CreatedDate { get ; set ; } public List<Genre> Genres { get ; set ; } public List<MediaFormat> Formats { get ; set ; } public List<MetaData> MetaData { get ; set ; } #region IAutoMapperAft...