0

我有四个类 - 两个视图模型和两个实体:

PhoneNumberTypeViewModel:

public class PhoneNumberTypeViewModel
{
    public int Id { get; private set; }

    public string Description { get; set; }

    public PhoneNumberTypeViewModel(int id, string description)
    {
        Id = id;
        Description = description;
    }
}

电话号码视图模型:

public class PhoneNumberViewModel
{
    public string PhNumber { get; set; }

    public PhoneNumberTypeViewModel PhoneType { get; set; }

    public PhoneNumberViewModel(string phNumber, PhoneNumberTypeViewModel phoneType)
    {
        PhNumber = phNumber;
        PhoneType = phoneType;
    }
}

电话号码类型:

public class PhoneNumberType : ValueObject
{
    public static readonly PhoneNumberType Home = new PhoneNumberType(1, "Home");

    public static readonly PhoneNumberType Office = new PhoneNumberType(2, "Office");

    public static readonly PhoneNumberType Cell = new PhoneNumberType(3, "Cell");

    public static readonly PhoneNumberType[] AllStatuses = { Home, Office, Cell };

    public int Id { get; }
    public string Description { get; private set;}

    private PhoneNumberType()
    {
    }

    public PhoneNumberType(int id, string description)
    {
        Id = id;
        Description = description;
    }
}

电话号码:

public class PhoneNumber : ValueObject
{
    public int Id { get;  private set; }

    [Phone]
    public string PhNumber { get; private set;}

    public PhoneNumberType PhoneType { get; }

    private PhoneNumber()
    {
    }

    public PhoneNumber(string phNumber, PhoneNumberType phoneType)
    {
        PhNumber = phNumber;
        PhoneType = phoneType;
    }
}

我使用 AutoMapper 来映射类:

var config1 = new MapperConfiguration(cfg => cfg.CreateMap<PhoneNumberType, PhoneNumberTypeViewModel>().ReverseMap());
var config2 = new MapperConfiguration(cfg => cfg.CreateMap<PhoneNumber, PhoneNumberViewModel>());

然后我尝试使用以下方法验证配置:

            config1.AssertConfigurationIsValid();
            config2.AssertConfigurationIsValid();

config2 上的验证会引发以下异常:

+       $exception  {"The following member on JobAssist.Services.ConnectionMgmt.API.Application.ViewModels.PhoneNumberViewModel cannot be mapped: \n\tPhoneType \nAdd a custom mapping expression, ignore, add a custom resolver, or modify the destination type JobAssist.Services.ConnectionMgmt.API.Application.ViewModels.PhoneNumberViewModel.\nContext:\n\tMapping to member PhoneType from JobAssist.Services.ConnectionMgmt.Domain.AggregatesModel.ConnectionManagerAggregate.PhoneNumber to JobAssist.Services.ConnectionMgmt.API.Application.ViewModels.PhoneNumberViewModel\nException of type 'AutoMapper.AutoMapperConfigurationException' was thrown."}   AutoMapper.AutoMapperConfigurationException

Config1 通过验证,为什么 Config2 会抛出这个错误?

4

1 回答 1

0

我发现了问题:在上面的代码中,我删除了对无效参数的检查。在 PhoneNumberViewModel 的构造函数中,我正在检查 phoneType 是否为空。我猜 Automapper 在构造实体后会调用 setter 方法。

于 2020-05-24T13:43:50.827 回答