我在我的ASP.NET MVC网站中使用AutoMapper将我的数据库对象映射到ViewModel对象,我试图使用几个配置文件来映射相同的类型,但使用另一个逻辑.我想通过阅读Matt的博客文章这样做,他说:
真正关键的部分是AutoMapper配置文件.您可以使用配置文件对配置进 也许在一个配置文件中,您可以通过一种方式格式化日期,而在另一种配置文 我在这里只使用一个配置文件.
所以我为一个案例创建了一个配置文件:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
还有另一个案例:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我找不到Mapper.Map<>()
指定配置文件的方法的任何重载.我也Configuration
没有运气看过这个物体.
最后注册的配置文件始终优先.
有没有办法为此目的使用配置文件?
Jim*_*ard 42
配置文件用于隔离应用于多个类型映射的常见配置,例如格式化.但是,类型映射仍然是全局的.您最好创建单独的Configuration对象,并为每个对象创建单独的MappingEngine.Mapper类只是每个上面的静态外观,带有一些生命周期管理.