在mvc中使用AutoMapper绑定自定义属性



我已经实现了简单的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; }
    }
}

my ViewModel class

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

在我有一个iccollection属性,当我试图映射这个属性,它显示我以下错误

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绑定这个自定义集合属性。

您需要在AreaPincodeAreaPincodeViewModel之间创建一个自定义映射:

Mapper.CreateMap<AreaPincode, AreaPincodeViewModel>()
  .ForMember(...)

这一行不需要:.ForMember(s => s.AreaPincode, d => d.MapFrom(t => t.AreaPincode))会自动匹配

当映射到CityViewModel中的AreaPincode时,需要从类型ICollection<AreaPincode>转换为类型ICollection<AreaPincodeViewModel>,即将类型AreaPincode的所有元素映射为类型AreaPincodeViewModel的元素。

创建一个从AreaPincodeAreaPincodeViewModel的映射。

Mapper.CreateMap<AreaPincode, AreaPincodeViewModel>()
...

一旦设置好了,AutoMapper就会处理剩下的工作。甚至不需要

这一行。
.ForMember(s => s.AreaPincode, d => d.MapFrom(t => t.AreaPincode));

因为AutoMapper会自动找出这个映射,因为属性名是相等的。

最新更新