0

我有一个基类和 3 个子类以及具有所有属性的单个视图模型。我想在我的控制器中创建操作以将此视图模型绑定到具体的子类型。

这是我的创建操作不起作用(我收到错误映射类型):

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(AdViewModel vm)
{
    if (ModelState.IsValid)
    {
         var ad = Mapper.Map<Ad>(vm);
        _context.Ads.Add(ad);
        _context.SaveChanges();
         return RedirectToAction("Index");
    }
    return View();
}

这是自动映射器配置:

Mapper.Initialize(config =>
        {
            config.CreateMap<AdViewModel, Ad>().ReverseMap();
            config.CreateMap<AdViewModel, Realty>().ReverseMap();
            config.CreateMap<AdViewModel, Auto>().ReverseMap();
            config.CreateMap<AdViewModel, Service>().ReverseMap();
        });

这是工作代码,但我怀疑使用它:

public IActionResult Create(AdViewModel vm)
{
    if (ModelState.IsValid)
    {
        if (vm.RealtyType != null)
        {
            var ad = Mapper.Map<Realty>(vm);
            _context.Add(ad);
        }
        else if (vm.AutoType != null)
        {
            var ad = Mapper.Map<Auto>(vm);
            _context.Add(ad);
        }
        else
        {
            var ad = Mapper.Map<Service>(vm);
            _context.Add(ad);
        }
        _context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View();
}
4

1 回答 1

0

您必须将逻辑放在某处创建正确的子类。如果你想在 Automapper 配置中隐藏它,你可以通过定义一个构造函数来实现。这仅在目标实体相关时才有效(我假设它AdRealty,Auto和的基类Service)。

// construct correct subtype of entity, depending on ViewModel state
var ctorFunc = new Func<AdViewModel, Ad>(vm => {
    if (vm.RealtyType != null) {
        return new Realty();
    }
    // etc.
});

// create correct subclass, map common properties of base class, 
// then dispatch to map properties of child class
CreateMap<AdViewModel, Ad>()
    // construct correct subclass of target entity
    .ConstructUsing(ctorFunc)
    // map common members to base class
    .ForMember(ent => ent.CommonField, o => o.MapForm(vm => vm.CommonField)
    // dispatch to mapping of child class
    // NOTE: this assumes that this profile was used to configure the static AutoMapper
    .AfterMap((vm, ent) => Mapper.Map(vm, ent, vm.GetType(), ent.GetType()));

// define rules for special members of child classes
CreateMap<AdViewModel, Realty>().ReverseMap();
// etc.

然后你应该可以var ad = Mapper.Map<Ad>(vm);成功调用。

于 2016-08-23T10:06:12.407 回答