简体   繁体   English

在Automapper中使用配置文件以不同的逻辑映射相同的类型

[英]Using Profiles in Automapper to map the same types with different logic

I am using AutoMapper in my ASP.NET MVC website to map my database objects to ViewModel objects and I am trying to use several profiles to map the same types, but using another logic. 我在我的ASP.NET MVC网站中使用AutoMapper将我的数据库对象映射到ViewModel对象,我试图使用几个配置文件来映射相同的类型,但使用另一个逻辑。 I had the idea of doing so by reading Matt's blog post where he says: 我想通过阅读Matt的博客文章这样做,他说:

The really key part is the AutoMapper configuration profile. 真正关键的部分是AutoMapper配置文件。 You can group configurations with profiles. 您可以使用配置文件对配置进 Maybe in one profile you format dates in one way, in another profile you format dates in another way. 也许在一个配置文件中,您可以通过一种方式格式化日期,而在另一种配置文 I'm just using one profile here. 我在这里只使用一个配置文件。

So I created a profile for one case: 所以我为一个案例创建了一个配置文件:

public class MyProfile : Profile
{
    protected override string ProfileName
    {
        get
        {
            return "MyProfile";
        }
    }

    protected override void Configure()
    {
        CreateMap<DateTime, String>().ConvertUsing<StringFromDateTimeTypeConverter>();
    }
}

public class StringFromDateTimeTypeConverter : ITypeConverter<DateTime, String>
{
    public string Convert(DateTime source)
    {
        return source.ToString("dd/mm/yyyy", CultureInfo.InvariantCulture);
    }
}

And another one for another case: 还有另一个案例:

public class MyProfile2 : Profile
{
    protected override string ProfileName
    {
        get
        {
            return "MyProfile2";
        }
    }

    protected override void Configure()
    {
        CreateMap<DateTime, String>().ConvertUsing<AnotherStringFromDateTimeTypeConverter>();
    }
}

public class AnotherStringFromDateTimeTypeConverter : ITypeConverter<DateTime, String>
{
    public string Convert(DateTime source)
    {
        return source.ToString("mm - yyyy", CultureInfo.InvariantCulture);
    }
}

However, I cannot find any overload of the Mapper.Map<>() method to specify a profile. 但是,我找不到Mapper.Map<>()方法的任何重载来指定配置文件。 I also had a look at the Configuration object with no luck. 我也看了一下没有运气的Configuration对象。
The last registered profile always takes precedence. 最后注册的配置文件始终优先。

Is there a way to use profiles for this purpose? 有没有办法为此目的使用配置文件?

Profiles are for segregating common configuration applied across several type maps, like formatting. 配置文件用于隔离应用于多个类型映射的常见配置,例如格式化。 However, type maps are still global. 但是,类型映射仍然是全局的。 You're better off creating separate Configuration objects, and creating a separate MappingEngine for each. 您最好创建单独的Configuration对象,并为每个对象创建单独的MappingEngine。 The Mapper class is merely a static facade over each of those, with some lifecycle management. Mapper类只是每个上面的静态外观,带有一些生命周期管理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM