我有一个使用继承的复杂对象,我使用自动映射器映射它,它在获取请求期间完美映射,但在发布请求期间,完全相同的代码无法正确映射初始化的类型。
让我解释。(见下面的代码)
在第一种情况下,当我在简单的 get 请求期间映射对象时,它映射得非常好,并且下面Parent类的属性A是其特定类型B或C.
但是当在帖子中发生完全相同的映射时,Parent属性的A类型是A!??
现在,代码是一样的,从数据库返回的数据模型是一样的。(我使用 nhibernate - 类型如我所料)唯一的区别是它是一个发布请求?!
在这种情况下,我应该了解 AutoMapper 吗?
类定义(ViewModel 遵循相同的结构):
public class A 
{
    public A Parent { get; set;}
}
public class B : A 
{ }
public class C : A 
{ }
并像这样映射:
CreateMap<A, AViewModel>()  
    .Include<B, BViewModel>()
    .Include<C, CViewModel>();
CreateMap<B, BViewModel>();
CreateMap<C, CViewModel>();
调用地图:
var aModel = _aManager.Get("same parameter");
var aViewModel = Mapper.Map<AViewModel>(aModel);
in编辑 #1 - 这描述了 post Action的逻辑:
    [Transaction] // Commits the nhibernate transaction on OnActionExecuted
    [HttpPost]
    public ActionResult UpdateA(OtherModelViewModel viewModel)
    { 
        var a = _aManager.Get("same parameter");
        var otherModel = Mapper.Map<OtherModel>(viewModel); 
        a.AddOtherModel(otherModel);
        _otherModelRepository.New(otherModel);
        // Eeek, writing this out I am seeing a problem here, I suspect this is where my problem would be, loading the model again from the db, after updating it in session without commiting it? I am going to change the logic and see if it fixes it.
        var aModel = _aManager.Get("same parameter");
        var aViewModel = Mapper.Map<AViewModel>(aModel);
        // return result.
    }