我有两节课:
public class Parametro
{
public int Id { get; set; }
public string Nombre { get; set; }
public int TipoDatoId { get; set; }
public TipoDato TipoDato { get; set; }
}
public class ParametroCreateViewModel
{
public string Nombre { get; set; }
public int TipoDatoId { get; set; }
}
当我以这种方式设置它_mapper.Map(model);我收到以下错误:
找到了未映射的成员。查看下面的类型和成员。添加自定义映射表达式,忽略,添加自定义解析程序或修改源/目标类型对于无匹配构造函数,添加无参数ctor,添加可选参数或映射所有构造函数参数ParametroCreateViewModel-> Parametro(目标成员list)ProyectoTest.ServiciosCliente.Application.Parametros.Commands.AddFParametro.ParametroCreateViewModel-> Calidda.ServiciosCliente.Domain.Parametros.Parametro(目标成员列表)未映射的属性:Id
但是当我按照这种方式尝试它时:Mapper.Map <ParametroCreateViewModel,Parametro>(model);
我的autofac如下:
builder.RegisterAssemblyTypes().AssignableTo(typeof(Profile));
builder.Register(c => new MapperConfiguration(cfg =>
{
foreach (var profile in c.Resolve<IEnumerable<Profile>>())
{
cfg.AddProfile(profile);
}
})).AsSelf().SingleInstance();
builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
我的automapperconfig是:
public class AutoMapperConfig : Profile
{
public static void Initialize()
{
Mapper.Initialize((config) =>
{
config.CreateMap<ParametroCreateViewModel, Parametro>()
.ForMember(dest => dest.Id, opt => opt.Ignore()).ReverseMap();
}
}
}
并声明我的global.asax:
AutofacConfig.Register();
AutoMapperConfig.Initialize();
GlobalConfiguration.Configure(WebApiConfig.Register);
看起来这里是几个问题的组合。您应该使用配置文件类加载某些程序集,并将它们注册为Profile
。在您的示例中,foreach循环不执行任何迭代,因为容器不包含Profile
的任何注册。要创建映射,您应该使用配置文件本身而不是静态Mapper
类。静态方法Initialize
未被调用,因此未创建映射。请考虑这个例子:
public class AutoMapperConfig : Profile
{
public AutoMapperConfig()
{
// Create mapping within profile in constructor
CreateMap<ParametroCreateViewModel, Parametro>()
// ignore both unmapped properties
.ForMember(dest => dest.Id, opt => opt.Ignore())
.ForMember(dest => dest.TipoDato, opt => opt.Ignore())
.ReverseMap();
}
}
[Test]
public void AutoMapperAutofacTest()
{
// Arrange
var builder = new ContainerBuilder();
// load certain assembly
builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(AutoMapperConfig)))
.AssignableTo<Profile>()
.As<Profile>(); // register as profile
builder.Register(c => new MapperConfiguration(cfg =>
{
foreach (var profile in c.Resolve<IEnumerable<Profile>>())
{
cfg.AddProfile(profile);
}
})).AsSelf().SingleInstance();
builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
var container = builder.Build();
var mapper = container.Resolve<IMapper>();
var param = new Parametro();
var viewModel = new ParametroCreateViewModel
{
Nombre = "Nombre",
TipoDatoId = 1
};
// Act
mapper.Map(viewModel, param);
//Assert
Assert.AreEqual(param.TipoDatoId, 1);
Assert.AreEqual(param.Nombre, "Nombre");
}
我用测试包装了这个例子,使它可以重现。希望能帮助到你。