我希望能够映射到IFoo.IBar.Name而不自己创建IBar类型的具体对象.
使用CreateMap级别的代理很容易做到:Mapper.CreateMap< Person,IFoo>(),但是如何为自定义内部接口类型成员实现它呢?
public class Test
{
[Fact]
public void MapToInnerInterface()
{
const int id = 1;
const string name = "Peter";
var person = new Person {Id = id, Name = name};
Mapper.CreateMap<Person, IFoo>()
.ForMember(dest => dest.Bar.Name, c => c.MapFrom(src => src.Name));
var mapResult = Mapper.Map<IFoo>(person);
Assert.Equal(id, mapResult.Id);
Assert.Equal(name, mapResult.Bar.Name);
}
}
public interface IFoo
{
int Id { get; set; }
IBar Bar { get; set; }
}
public interface IBar
{
string Name { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
解决方法:
您可以通过将外部类(Person)映射到内部接口(IBar),然后在Person→IFoo映射中利用该映射来完成此操作.
Mapper.CreateMap<Person, IFoo>()
.ForMember(dest => dest.Bar, opt => opt.MapFrom(src => src));
Mapper.CreateMap<Person, IBar>();
IFoo foo = Mapper.Map<IFoo>(person);
Console.WriteLine(foo.Bar.Name); // Peter
Console.WriteLine(foo.Id); // 1
正如您所期望的,将创建两个代理对象,一个实现IFoo,另一个实现IBar.
例如:https://dotnetfiddle.net/VuyT1K