使用DDD自动映射和验证配置

时间:2017-07-28 12:47:44

标签: c# automapper

我在DDD方法中有简单的域模型,所以只有创建实例的方法才是使用构造函数。

public CashCaseDifference(
        double amount,
        double originalAmount,
        double originalFcyAmount,
        CashCaseDifferenceCurrency currency,
        CashCaseDifferenceSource source,
        CashCaseDifferenceType type)
    {
        this.Amount = amount;
        this.OriginalAmount = originalAmount;
        this.OriginalFcyAmount = originalFcyAmount;
        this.Currency = currency;
        this.Source = source;
        this.Type = type;
    }

当我尝试对配置进行单元测试时,我遇到了问题。

映射配置文件:

this.CreateMap<CashCaseOut, CashCaseDifference>()
                .ConstructUsing(source => new CashCaseDifference(
                    source.Amount.GetValueOrDefault(),
                    source.OriginalAmount.GetValueOrDefault(),
                    source.OriginalFcyAmount.GetValueOrDefault(),
                    (CashCaseDifferenceCurrency) source.Currency.GetValueOrDefault(),
                    (CashCaseDifferenceSource) source.SourceOfDifference.GetValueOrDefault(),
                    (CashCaseDifferenceType) source.Type.GetValueOrDefault()));

我的单元测试方法:

  Mapper.Initialize(
            cfg => { cfg.AddProfile(new CashCaseOutToCashCaseDifference()); });
        Mapper.AssertConfigurationIsValid(););

返回未映射属性的错误:

Unmapped members were found. Review the types and members below.

&#34;添加自定义映射表达式,忽略,添加自定义解析程序或修改源/目标类型 对于没有匹配的构造函数,添加一个no-arg ctor,添加可选参数,或映射所有构造函数参数&#34;

Unmapped properties: Source

编辑:

施工也不行。

      Mapper.Initialize(cfg =>
        {
            cfg.AddProfile(new CashCaseOutToCashCaseDifference());
        });
        Mapper.AssertConfigurationIsValid();

  public CashCaseOutToCashCaseDifference()
    {
        this.CreateMap<
                CashDiffMS.Client.Models.CashCaseOut,
                Core.CashCases.Domain.Differences.CashCaseDifference>()
            .ForCtorParam("amount", opt => opt.MapFrom(src => src.Amount))
            .ForCtorParam("originalAmount", opt => opt.MapFrom(src => src.OriginalAmount))
            .ForCtorParam("originalFcyAmount", opt => opt.MapFrom(src => src.OriginalFcyAmount))
            .ForCtorParam("currency", opt => opt.MapFrom(src => src.Currency))
            .ForCtorParam("source", opt => opt.MapFrom(src => src.SourceOfDifference))
            .ForCtorParam("type", opt => opt.MapFrom(src => src.Type));
    }

public CashCaseDifference(
        double amount,
        double originalAmount,
        double originalFcyAmount,
        CashCaseDifferenceCurrency currency,
        CashCaseDifferenceSource source,
        CashCaseDifferenceType type)
    {
        this.Amount = amount;
        this.OriginalAmount = originalAmount;
        this.OriginalFcyAmount = originalFcyAmount;
        this.Currency = currency;
        this.Source = source;
        this.Type = type;
    }

结果相同:Unmapped properties: Source

1 个答案:

答案 0 :(得分:0)

那是因为你手工制作。你应该让AM去做。文档为here