一种类型的属性映射到另一种类型的实例

时间:2016-03-14 22:25:36

标签: c# automapper

我正在使用automapper将视图模型和实体模型相互映射,一切都很好,但现在我有一个不同的场景,AutoMapper无法映射我的类型。

我的视图模型:

   public class CriminalSearchViewModel
   {

    public CriminalSearchParamsViewModel SearchParameters { get; set; }

    public SelectList GenderSelectList { get; set; }

    public SelectList NationalitySelectList { get; set; }

    public SelectList CrimeSelectList { get; set; }

    public SelectList CriminalStatusSelectList { get; set; }
}

第二视图模型:

public class CriminalSearchParamsViewModel
{
    [Required]
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int? GenderID { get; set; }

    public int? StatusID { get; set; }

    public string CNIC { get; set; }

    public int? AgeFrom { get; set; }

    public int? AgeTo { get; set; }

    public double? Height { get; set; }

    public int Weight { get; set; }

    public int? NationalityID { get; set; }
}

和我的商业模式:

public class CriminalSearch
{

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int? GenderID { get; set; }

    public int? StatusID { get; set; }

    public string CNIC { get; set; }

    public int? AgeFrom { get; set; }

    public int? AgeTo { get; set; }

    public double? Height { get; set; }

    public int Weight { get; set; }

    public int? NationalityID { get; set; }

}

我已经定义了映射:

Mapper.CreateMap<CriminalSearch, CriminalSearchParamsViewModel>();

也尝试了这个:

 Mapper.CreateMap<CriminalSearchParamsViewModel,CriminalSearchViewModel>()
  .ForMember(dest => dest.SearchParameters, opt =>
     opt.MapFrom(src => Mapper.Map<CriminalSearchParamsViewModel, CriminalSearch>(src)));

在控制器中我想尝试:

public ActionResult Search(CriminalSearchViewModel searchVM)
{
    if (ModelState.IsValid)
    {
        var searchParams = searchVM.SearchParameters;
        var criminalSearch = AutoMapper.Mapper.Map<CriminalSearch>(searchParams);
        _criminalService.SearchCriminals(criminalSearch);
    }
        return View();
}

但它总是抛出异常:

  
    

缺少类型映射配置或不支持的映射。

         

映射类型:     CriminalSearchParamsViewModel - &gt; CriminalSearch     NationalCriminals.UI.ViewModels.CriminalSearchParamsViewModel - &gt; NationalCriminals.Core.Models.CriminalSearch

         

目的地路径:     CriminalSearch

         

来源价值:     NationalCriminals.UI.ViewModels.CriminalSearchParamsViewModel

  

任何人都可以告诉我出了什么问题?

1 个答案:

答案 0 :(得分:2)

您只需要更改方法CreateMap中的通用参数的顺序:

Mapper.CreateMap<CriminalSearchParamsViewModel,CriminalSearch>()

这是因为第一个通用arg是类型,第二个是目的地,它不是两种方式,如果你想要,你必须声明两者从一种类型映射到另一种类型,反之亦然:

Mapper.CreateMap<CriminalSearchParamsViewModel,CriminalSearch>()
Mapper.CreateMap<CriminalSearch,CriminalSearchParamsViewModel>()

方法CreateMap的描述如下:

AutoMapper.Mapper.CreateMap<SourceClass, DestinationClass>();
  

建议:Using AutoMapper: Creating Mappings