从3.3.1到4.0.4的AutoMapper Update无法映射

时间:2015-08-20 15:09:12

标签: c# automapper

以下代码在AutoMapper 3.3.1中完美运行。

public ProductVM GetProductDetailVM(int id)
{
    try
    {
        Mapper.CreateMap<Product, ProductVM>();
        var model = this._productRep.SingleOrDefault(d => d.ProductId== id);
        ProductVM vm = Mapper.Map<Product, ProductVM>(model);
        vm.Status = this._statusRep.FirstOrDefault(d => d.StatusID == model.StatusID);

        vm.FullName = vm.ForeName + " "
                      + (string.IsNullOrEmpty(vm.MiddleName.Trim()) ? string.Empty : vm.MiddleName + " ")
                      + vm.SurName;
        return vm;
    }
    catch (Exception)
    {
        return null;
    }
}

但是,我决定使用最新版本的AutoMapper(4.0.4)而且我收到以下错误说

“缺少类型映射配置或不支持的映射。\ n \ nMapping”

导致这个问题的原因是什么?

1 个答案:

答案 0 :(得分:2)

我也遇到了同样的问题,这让我发疯了。我刚刚意识到这是从v3.3.1到v4.0.4的更新。以下UnitTest说明了错误。我不知道他们引入了哪个更改但是如果有一个带有IEnumerable&lt;的构造函数则会中断。 SelectListItem&gt; testList参数。

public class TestEntity
{
    public int Id { get; set; }
}

public class TestEntityViewModel
{
    public TestEntityViewModel()
    {

    }

    public TestEntityViewModel(IEnumerable<SelectListItem> testList)
    {
        TestList = testList;
    }

    public int Id { get; set; }
    public virtual IEnumerable<SelectListItem> TestList { get; set; }
}


[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        Mapper.CreateMap<TestEntity, TestEntityViewModel>()
            .ForMember(m => m.TestList, opt => opt.Ignore());

        var entity = new TestEntity();

        var viewModel = Mapper.Map<TestEntityViewModel>(entity);


        Assert.IsNotNull(viewModel);
    }
}