2013-03-28 61 views
1

我已经实现了简单的MVC3应用程序,我已经使用AutoMapper将我的数据库表绑定到ViewMode,但我无法使用automapper绑定复杂的ViewModel。使用MVC3中的AutoMapper绑定自定义属性

这是我的领域类

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

    } 

住在我当我尝试这个属性就告诉我映射以下错误

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. 
一个ICollection的属性

以下代码的东西我写在我的Global.asax

Mapper.CreateMap<City, CityViewModel>() 
      .ForMember(s => s.DistrictID, d => d.Ignore()) 
      .ForMember(s => s.AreaPincode, d => d.MapFrom(t => t.AreaPincode)); 

请让我知道我应该如何使用automapper绑定此自定义集合属性。

回答

1

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

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

而且还有在该行中没有必要:.ForMember(s => s.AreaPincode, d => d.MapFrom(t => t.AreaPincode))它会自动匹配

+0

感谢它为我工作.. – Shivkumar 2013-03-28 05:51:12

0

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

为此,请创建一个从AreaPincodeAreaPincodeViewModel的新映射。

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

一旦这个到位,AutoMapper应该照顾其余的。你甚至不需要这条线

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

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