【问题标题】:Automapper Project() to IEnumerable and single ObjectsAutomapper Project() 到 IEnumerable 和单个对象
【发布时间】:2017-04-27 06:10:03
【问题描述】:

我有两个类将与另一个类映射。 MyViewClassMyDomainClass

public class EntityMapProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<MyDomainClass, MyViewClass>();
    }
}

所以我需要一个扩展方法来将域对象映射到视图对象。

public static class MyClassMapper
{
    public static MyViewClass ToView(this MyDomainClass obj)
    {
        return AutoMapper.Mapper.Map<MyDomainClass, MyViewClass>(obj);
    }

    public static IEnumerable<MyViewClass> ToView(this IEnumerable<MyDomainClass> obj)
    {
        return AutoMapper.Mapper.Map<IEnumerable<MyDomainClass>, IEnumerable<MyViewClass>>(obj);
    }
}

但是我有很多域和视图类。所以我需要创建这么多的扩展方法和类。

有什么方法可以通用吗?

【问题讨论】:

    标签: c# mapping automapper automapper-3


    【解决方案1】:

    自动映射器已经在使用泛型,所以我使用直接映射器而不是扩展名没有任何问题,例如

    var view = AutoMapper.Mapper.Map<MyDomainClass, MyViewClass>(domain);
    

    但是您可以为 IEnumerable 映射编写扩展:

    public static IEnumerable<TView> MapEnumerable<TDomainModel, TView>(this IEnumerable<TDomainModel> domainEnumerable)
                where TDomainModel : class
                where TView : class
            {
                return AutoMapper.Mapper.Map<IEnumerable<TDomainModel>, IEnumerable<TView>>(domainEnumerable);
            }
    

    并像这样使用它:

    IEnumerable<MyViewClass> views = domainEnumerable.MapEnumerable<MyDomainClass, MyViewClass>();
    

    更新: 单域模型扩展

    public static TView MapDomain<TDomainModel, TView>(this TDomainModel domainModel)
                where TDomainModel : class
                where TView : class
            {
                return AutoMapper.Mapper.Map<TDomainModel, TView>(domainModel);
            }
    

    【讨论】:

    • Automapper 有泛型,但我需要一直使用 AutoMapper.Mapper.Map。如果我创建扩展方法,我可以在任何地方使用它。谢谢。
    • 我也用单域模型地图扩展更新了答案
    猜你喜欢
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 2021-04-28
    • 2013-11-01
    相关资源
    最近更新 更多