【问题标题】:Does AutoMapper support Open Generics with inheritance from a non-generic base class?AutoMapper 是否支持从非泛型基类继承的开放泛型?
【发布时间】:2018-06-06 19:15:48
【问题描述】:

AutoMapper 版本号为 7.0.0。

参加以下课程:

public class Person
{
    public string Name { get; set; }
    public List<BarBase> BarList { get; set; }
}

public class PersonModel
{
    public string Name { get; set; }
    public List<BarModelBase> BarList { get; set; }
}

abstract public class BarBase
{
    public int Id { get; set; }
}

public class Bar<T> : BarBase
{
    public T Value { get; set; }
}

abstract public class BarModelBase
{
    public int Id { get; set; }
}

public class BarModel<T> : BarModelBase
{
    public T Value { get; set; }
}

Person 具有 BarList 类型的属性 List&lt;BarBase&gt;。 BarBase 是一个抽象类,具有通用的具体实现 Bar&lt;T&gt;;该列表需要包含多种类型的T。

以下两种配置有效。注释掉的部分不像 cmets 中解释的那样工作。

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap(typeof(BarBase), typeof(BarModelBase))
       .Include(typeof(Bar<string>), typeof(BarModel<string>));

    cfg.CreateMap(typeof(Bar<string>), typeof(BarModel<string>));
    cfg.CreateMap(typeof(Person), typeof(PersonModel));
});

var config = new MapperConfiguration(cfg =>
{
    //Fails with: System.NullReferenceException : Object reference not set to an instance of an object.
    //cfg.CreateMap(typeof(BarBase), typeof(BarModelBase)).As(typeof(BarModel<>));

    //Fails with:  Missing map from AutoMapper.UnitTests.OpenGenerics+Bar`1[T] to AutoMapper.UnitTests.OpenGenerics+BarModel`1[T]. Create using Mapper.CreateMap<Bar`1, BarModel`1>.
    //cfg.CreateMap(typeof(BarBase), typeof(BarModelBase))
    //   .Include(typeof(Bar<>), typeof(BarModel<>));

    cfg.CreateMap<BarBase, BarModelBase>().ConvertUsing((source, destination, context) =>
    {
        System.Type sourceType = source.GetType();
        System.Type structType = sourceType.GetGenericArguments()[0];

        return (BarModelBase)context.Mapper.Map(source, sourceType, typeof(BarModel<>).MakeGenericType(structType));
    });


    cfg.CreateMap(typeof(Person), typeof(PersonModel));
    cfg.CreateMap(typeof(Bar<>), typeof(BarModel<>));
});

验证任一配置是否有效:

Person person = new Person
{
    Name = "Jack",
    BarList = new List<BarBase>
    {
        new Bar<string>{ Id = 1, Value = "One" },
        new Bar<string>{ Id = 2, Value = "Two" }
    }
};

PersonModel personMapped = config.CreateMapper().Map<PersonModel>(person);

Assert.Equal("One", ((BarModel<string>)personMapped.BarList[0]).Value);

问题:如果没有转换器(“ConvertUsing”)或显式映射每个封闭的泛型类型,我无法让 AutoMapper 的开放泛型适用于这种情况(Generic&lt;T&gt; 扩展Non-Generic)。

问题:我错过了什么? - 我可以在这里使用开箱即用的类型映射配置而不使用转换器吗?

【问题讨论】:

    标签: c# automapper open-generics


    【解决方案1】:

    AutoMapper issue log 确认当前版本中此类映射需要转换器。

    【讨论】:

    • 试试MyGet 构建。
    • 升级确实有效。感谢您的快速周转。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2015-10-28
    • 2021-07-28
    相关资源
    最近更新 更多