【问题标题】:Automapper - map to Interface type property without creating concrete classAutomapper - 映射到接口类型属性而不创建具体类
【发布时间】:2014-11-01 11:06:21
【问题描述】:

我希望能够映射到 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; }
}

【问题讨论】:

    标签: c# interface proxy automapper


    【解决方案1】:

    您可以通过将外部类 (Person) 映射到内部接口 (IBar) 来完成此操作,然后在 PersonIFoo 映射中利用该映射。

    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

    【讨论】:

    • 这是正在寻找的答案 - 还不能投票。非常感谢。
    【解决方案2】:

    我希望能够映射到 IFoo.IBar.Name 而无需自己创建 IBar 类型的具体对象

    您如何期望 AutoMapper 知道 IBar 接口使用什么具体类型?如您所知,您不能拥有接口的实例。并且有人必须指定哪个是这种具体类型,而这绝对不是 AutoMapper 能够做的事情。

    您应该在 IBar 类型或 AfterMap 选项上使用自定义解析器,以便指示应该如何完成此映射。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多