我已经实现了简单的 MVC3 应用程序,其中我使用 AutoMapper 将我的数据库表绑定到 ViewMode,但我无法使用 automapper 绑定复杂的 ViewModel。
这是我的域类
namespace MCQ.Domain.Models
{
public class City
{
public City()
{
this.AreaPincode = new List<AreaPincode>();
}
public long ID { get; set; }
public string Name { get; set; }
public int DistrictID { get; set; }
public virtual ICollection<AreaPincode> AreaPincode { get; set; }
public virtual District District { get; set; }
}
}
我的 ViewModel 类
public class CityViewModel
{
public CityViewModel()
{
this.AreaPincode = new List<AreaPincodeViewModel>();
}
public long ID { get; set; }
public string Name { get; set; }
public int DistrictID { get; set; }
public ICollection<AreaPincodeViewModel> AreaPincode { get; set; }
}
因为当我尝试映射此属性时,我有一个 ICollection 属性,它显示以下错误
The following property on MCQ.ViewModels.AreaPincodeViewModel cannot be mapped:
AreaPincode
Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type MCQ.ViewModels.AreaPincodeViewModel.
Context:
Mapping to property AreaPincode from MCQ.Domain.Models.AreaPincode to MCQ.ViewModels.AreaPincodeViewModel
Mapping to property AreaPincode from System.Collections.Generic.ICollection`1[[MCQ.Domain.Models.AreaPincode, MCQ.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.ICollection`1[[MCQ.ViewModels.AreaPincodeViewModel, MCQ, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
Mapping from type MCQ.Domain.Models.City to MCQ.ViewModels.CityViewModel
Exception of type 'AutoMapper.AutoMapperConfigurationException' was thrown.
以下我在 Global.asax 中编写的代码内容
Mapper.CreateMap<City, CityViewModel>()
.ForMember(s => s.DistrictID, d => d.Ignore())
.ForMember(s => s.AreaPincode, d => d.MapFrom(t => t.AreaPincode));
请让我知道我应该如何使用 automapper 绑定这个自定义集合属性。