Automapper双重失败?属性

时间:2013-04-11 13:15:09

标签: asp.net-mvc asp.net-mvc-4 automapper automapper-2

我正在使用AutoMapper将Domain对象映射到控制器中的ViewModel对象。在尝试添加双重属性之前,一切正常。我开始收到以下错误:

Missing type map configuration or unsupported mapping.

Mapping types:
Address -> AddressModel
Domain.Address -> Web.Models.AddressModel

Destination path:
AccountAddressModel.Address.Address

Source value:
Domain.Address

My Address类和AddressModel类都有两个名为Longitude和Latitude的属性。这些属性(在两个类中)都定义为double?。如果我注释掉这些属性,一切正常。如果我将所有这些属性简单地加倍,那么一切正常。这只是双倍?导致问题的原因。

我正在使用通过NuGet下载的 AutoMapper 2.2.1

我在其他帖子中读到这个问题与nullables应该是固定的。这让我相信我可能会做一些不同的事情,所以我要发布我的代码,看看是否有人可以看到可能存在问题的东西:

DOMAIN MODELS

public class AccountAddress 
{
    public int Id { get; set; }
    public int AccountId { get; set; }
    public int AddressId { get; set; }
    public Address Address { get; set; }
    ...
}

public class Address : IUserTrackingEntity
{
    public int Id { get; set; }
    public string Addressee { get; set; }
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    ...
    public double? Longitude { get; set; }
    public double? Latitutde { get; set; }
} 

查看模型

public class AccountAddressEditModel
{
    public string AccountName { get; set; }
    public AccountAddressModel Address { get; set; }
    public IList<Country> CountriesList { get; set; }
    ...
}

public class AccountAddressModel
{
    public AccountAddressModel()
    {
        Address = new AddressModel();
    }
    public int AccountId { get; set; }
    public int AddressId { get; set; }
    public int Id { get; set; }
    public AddressModel Address { get; set; }
}

public class AddressModel
{
    public int Id { get; set; }
    public string Addressee { get; set; }
    [Required(ErrorMessage="A street address is required.")]
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    ...
    public double? Longitude { get; set; }
    public double? Latitude { get; set; }
}

我的控制器中的映射代码

//Get an AccountAddress
address = _context.AccountAddresses.SingleOrDefault(ad => ad.Id == 12345);

model = new AccountAddressEditModel();

Mapper.CreateMap<AccountAddress, AccountAddressModel>();
Mapper.CreateMap<AccountAddress, AddressModel>();

Mapper.Map(address, model.AccountAddress);

是否还有其他人遇到此问题或找到解决方案?

1 个答案:

答案 0 :(得分:1)

该行

 Mapper.CreateMap<AccountAddress, AddressModel>();

应改为

Mapper.CreateMap<Address, AddressModel>();

这是因为您要将Address类映射到AddressModel类。