如何从ViewModel映射到Model

时间:2015-08-04 15:41:25

标签: c# asp.net-mvc automapper

我有一个像这样的模型和ViewModel

public class Estate : BaseEntity
{       
    public virtual BaseInformation floorType { get; set; }     
}

public class BaseInformation:BaseEntity 
{ 
    public string Name { get; set; }     
    public virtual BaseInformationHeader Master { get; set; }
}

public class EstateViewModel : BaseEntityViewModel
{       
    public  long floorType { get; set; }     
}

控制器中的代码:

[HttpPost]
public long save(EstateViewModel estateViewModel)
{
    Estate entity = new Estate();
    BaseInformation bi = new BaseInformation();
    bi.id = 1;
    entity.floorType = bi;
    EstateViewModel ev = new EstateViewModel(); 
    Mapper.CreateMap<EstateViewModel, Estate>();
    var model = AutoMapper.Mapper.Map<EstateViewModel,Estate>(estateViewModel);

    return estateRepository.save(entity);
}

执行操作时,AutoMapper会抛出以下异常:

  

类型&#39; AutoMapper.AutoMapperMappingException&#39;的例外情况发生了   在AutoMapper.dll中但未在用户代码中处理

是什么导致这种情况发生?

2 个答案:

答案 0 :(得分:2)

我的问题解决方案在这里找到: http://cpratt.co/using-automapper-creating-mappings/ 代码是这样的:

AutoMapper.Mapper.CreateMap<PersonDTO, Person>()
.ForMember(dest => dest.Address,
           opts => opts.MapFrom(
               src => new Address
               {
                   Street = src.Street,
                   City = src.City,
                   State = src.State,
                   ZipCode = src.ZipCode
               }));

答案 1 :(得分:0)

查看内部异常 - 它可以很好地描述问题。我还会考虑在应用程序启动时调用的其他地方以静态方法设置所有CreateMap调用:

public class AutoMapperConfiguration
{
    public static void Configure()
    {
         Mapper.CreateMap<EstateViewModel, Estate>();          
    }
}

然后在Global.asax:

protected void Application_Start()
{
    AutoMapperConfiguration.Configure();
}

[更新] - 将属性映射到具有不同名称的其他属性:

Mapper.CreateMap<ViewModel, Model>()
                  .ForMember(dest => dest.Id, o => o.MapFrom(src => src.DestinationProp));

您遇到的问题是源属性是long,而目标是复杂类型 - 您不能从源映射到目标,因为它们不是同一类型。

[更新2]

如果BaseInformation.Id很长,那么你就可以这样做了:

Mapper.CreateMap<ViewModel, Model>()
                  .ForMember(dest => dest.Id, o => o.MapFrom(src => src.floorType ));

你的模特虽然不是很清楚。