Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

c# - 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. I had the idea of doing so by reading Matt's blog post where he says:

The really key part is the AutoMapper configuration profile. 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. I also had a look at the Configuration object with no luck.
The last registered profile always takes precedence.

Is there a way to use profiles for this purpose?

question from:https://stackoverflow.com/questions/2183401/using-profiles-in-automapper-to-map-the-same-types-with-different-logic

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. The Mapper class is merely a static facade over each of those, with some lifecycle management.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...