Created
August 29, 2013 14:26
-
-
Save hyrmn/6378802 to your computer and use it in GitHub Desktop.
A Quick (and not best) way to use resolveusing for custom AutoMapper interestingness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Shouldly; | |
public class PhotoModel | |
{ | |
public string Name { get; set; } | |
public string Url { get; set; } | |
} | |
public class TargetModel | |
{ | |
public string FavoriteColor { get; set; } | |
public IEnumerable<PhotoModel> Photos { get; set; } | |
} | |
public class Photo | |
{ | |
public string Name { get; set; } | |
public string Filename { get; set; } | |
} | |
public class DomainSource | |
{ | |
public int Id { get; set; } | |
public string FavoriteColor { get; set; } | |
public IEnumerable<Photo> Photos { get; set; } | |
} | |
public class PhotoResolver : AutoMapper.ValueResolver<DomainSource, IEnumerable<PhotoModel>> | |
{ | |
protected override IEnumerable<PhotoModel> ResolveCore(DomainSource source) | |
{ | |
if (source.Photos == null || !source.Photos.Any()) | |
{ | |
throw new Exception("dude, this is a photo site, we should like have photos"); | |
} | |
return AutoMapper.Mapper.Map<IEnumerable<Photo>, IEnumerable<PhotoModel>>(source.Photos); | |
} | |
} | |
public class MyMappingTests | |
{ | |
public MyMappingTests() | |
{ | |
AutoMapper.Mapper.CreateMap<Photo, PhotoModel>() | |
.ForMember( | |
model => model.Url, opt => opt.MapFrom(domain => "http://dontreallydothis.com/images/" + domain.Filename)); | |
AutoMapper.Mapper.CreateMap<DomainSource, TargetModel>() | |
.ForMember(model => model.Photos, opt => opt.ResolveUsing<PhotoResolver>()); | |
} | |
public void MappingWithPhotosWorks() | |
{ | |
var someDomain = new DomainSource() | |
{ | |
Id = 1, | |
FavoriteColor = "Blue", | |
Photos = new List<Photo> { new Photo { Filename = "A_cat.png", Name = "a cat" } } | |
}; | |
var targetModel = AutoMapper.Mapper.Map<TargetModel>(someDomain); | |
targetModel.FavoriteColor.ShouldBe("Blue"); | |
targetModel.Photos.ShouldNotBeEmpty(); | |
} | |
public void MappingWithoutPhotosMakesOurWorldFallApart() | |
{ | |
var someDomain = new DomainSource() | |
{ | |
Id = 1, | |
FavoriteColor = "Blue", | |
}; | |
Should.Throw<Exception>(() => AutoMapper.Mapper.Map<TargetModel>(someDomain)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment