2

我已经实现了简单的 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 绑定这个自定义集合属性。

4

2 回答 2

2

您需要在AreaPincode和之间创建自定义映射AreaPincodeViewModel

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

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

于 2013-03-28T05:39:48.650 回答
1

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

为此,请创建一个从AreaPincode到的新映射AreaPincodeViewModel

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

一旦这到位,AutoMapper 应该负责其余的工作。你甚至不需要这条线

.ForMember(s => s.AreaPincode, d => d.MapFrom(t => t.AreaPincode));

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

于 2013-03-28T05:41:44.533 回答