Can AutoMapper create a map for an interface and then map with a derived type?
Posted
by
TheCloudlessSky
on Stack Overflow
See other posts from Stack Overflow
or by TheCloudlessSky
Published on 2010-12-26T15:07:36Z
Indexed on
2010/12/27
0:53 UTC
Read the original article
Hit count: 147
c#
|automapper
I have an interface IFoo:
public interface IFoo
{
int Id { get; set; }
}
And then a concrete implementation:
public class Bar : IFoo
{
public int Id { get; set; }
public string A { get; set; }
}
public class Baz : IFoo
{
public int Id { get; set; }
public string B { get; set; }
}
I'd like to be able to map all IFoo
but specifying their derived type instead:
Mapper.CreateMap<int, IFoo>().AfterMap((id, foo) => foo.Id = id);
And then map (without explicitly creating maps for Bar and Baz):
var bar = Mapper.Map<int, Bar>(123);
// bar.Id == 123
var baz = Mapper.Map<int, Baz>(456);
// baz.Id == 456
But this doesn't work in 1.1. I know I could specify all Bar
and Baz
but if there are 20 of these, I'd like to not have to manage them and rather just have what I did above for creating the map. Is this possible?
© Stack Overflow or respective owner