Tec*_*Guy 6 c# asp.net-mvc automapper
我在 asp.net C# 项目中实现了 Auto Mapper,但出现错误:
Mapper 不包含 Initialize 的定义
我试过这个例子链接在这里
我已经粘贴了我的代码:
namespace NewsWeb.Web.Infrastructure
{
public class AutomapperWebProfile:Profile
{
public AutomapperWebProfile()
{
CreateMap<DistrictDTO, District>().ReverseMap();
}
public static void Run()
{
Mapper.Initialize(a =>
{
a.AddProfile<AutomapperWebProfile>();
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的 Golbal.asax.cs 文件中:
AutomapperWebProfile.Run();
Run Code Online (Sandbox Code Playgroud)
Sta*_*sky 12
方法Mapper.Initialize自 v9.0.0 ( doc )版本起已过时,您需要MapperConfiguration改用 ( doc )。
var config = new MapperConfiguration(cfg => {
cfg.AddProfile<AutomapperWebProfile>();
});
var mapper = config.CreateMapper();
// or
var mapper = new Mapper(config);
Run Code Online (Sandbox Code Playgroud)
在 Golbal.asax 中使用静态方法初始化映射器不是一个灵活的解决方案。我建议直接在自定义映射器类中创建一个配置。
public interface IFooMapper
{
Foo Map(Bar bar);
}
public class FooMapper : IFooMapper
{
private readonly IMapper mapper;
public FooMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<FooProfile>();
});
mapper = config.CreateMapper();
}
public Foo Map(Bar bar) => mapper.Map<Foo>(bar);
}
Run Code Online (Sandbox Code Playgroud)