gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:28:24 25 4
gpt4 key购买 nike

我正在使用 automapper 相互映射 View 模型和实体模型,一切都很好,但现在我遇到了一些不同的情况,AutoMapper 无法映射我的类型。

我的 View 模型:

   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; }
}

第二个 View 模型:

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)));

在 Controller 中我正在尝试:

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

但它总是抛出异常:

Missing type map configuration or unsupported mapping.

Mapping types: CriminalSearchParamsViewModel -> CriminalSearch NationalCriminals.UI.ViewModels.CriminalSearchParamsViewModel -> NationalCriminals.Core.Models.CriminalSearch

Destination path: CriminalSearch

Source value: NationalCriminals.UI.ViewModels.CriminalSearchParamsViewModel

谁能告诉我哪里出了问题?

最佳答案

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

Mapper.CreateMap<CriminalSearchParamsViewModel,CriminalSearch>()

那是因为第一个泛型参数是Source类型,第二个是Destination,它不是双向的,如果你想,你必须声明两者从一种类型映射到另一种类型,反之亦然:

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

CreateMap 方法描述如下:

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

Suggest: Using AutoMapper: Creating Mappings

关于c# - 一种类型的属性映射到另一种类型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35999282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com