Created
May 14, 2020 20:01
-
-
Save frankhale/fe9159b4c7df9bf5d8cfd7656cd816f1 to your computer and use it in GitHub Desktop.
Map single object to list of objects in AutoMapper
This file contains hidden or 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 AutoMapper; | |
using System.Collections.Generic; | |
namespace AutoMapperSandbox | |
{ | |
public class SingleObjectToListConverter<T> : ITypeConverter<T, List<T>> | |
{ | |
public List<T> Convert(T source, List<T> destination, ResolutionContext context) | |
{ | |
return new List<T>() { source }; | |
} | |
} | |
public class Baz | |
{ | |
public string Qrs { get; set; } | |
} | |
public class Foo | |
{ | |
public string Xyz { get; set; } | |
public List<Baz> Baz { get; set; } | |
} | |
public class FooDto | |
{ | |
public string Xyz { get; set; } | |
public Baz Baz { get; set; } | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var config = new MapperConfiguration(cfg => | |
{ | |
cfg.CreateMap<Baz, List<Baz>>().ConvertUsing<SingleObjectToListConverter<Baz>>(); | |
cfg.CreateMap<Foo, FooDto>().ReverseMap(); | |
}); | |
var mapper = new Mapper(config); | |
var f = new FooDto() | |
{ | |
Xyz = "Testing", | |
Baz = new Baz() { Qrs = "Hello, World!" } | |
}; | |
var x = mapper.Map<Foo>(f); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment