自动映射器9列表映射不起作用asp.net核心

时间:2019-09-04 05:23:05

标签: c# asp.net asp.net-core automapper

我已经将Automapper更新到9.0,并且先前的代码已损坏。我在用

 <PackageReference Include="AutoMapper" Version="6.2.2" />
 <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="3.2.0" />

我正在尝试按照此代码映射列表

 public class ProjectBudgetSummaryProfile : Profile
    {
        public ProjectBudgetSummaryProfile()
        {
            CreateMap<ProjectBudgetSummaryViewModel, HdsBudgetSummary>();
            CreateMap<ProjectBudgetSummaryViewModel, CdsBudgetSummary>();
        }
    }

var finance = _mapper.Map<List<ProjectBudgetSummaryViewModel>>(budgetSummaries)


 public class ProjectBudgetSummaryViewModel
    {
        public decimal? CurrentApproval { get; set; }
        public decimal? CurrentForecast { get; set; }
        public decimal? Delta { get; set; }
        public string FinancialItemDescription { get; set; }
        public decimal? ForecastDelta { get; set; }
        public decimal? PreviousForecast { get; set; }
        public long? ForecastId { get; set; }
    }

public class HdsBudgetSummary : BudgetSummary
    {
    }

 public class BudgetSummary
    {
        public decimal? CurrentApproval { get; set; }
        public decimal? CurrentForecast { get; set; }
        public decimal? Delta { get; set; }
        public string FinancialItemDescription { get; set; }
        public decimal? ForecastDelta { get; set; }
        public decimal? PreviousForecast { get; set; }
        public int ProjectNumber { get; set; }
        public long? ForecastId { get; set; }
    }

配置设置

 public virtual IServiceProvider ConfigureServices(IServiceCollection services)
        {
            ConfigureMapping(services);
            return ServiceProvider;
        }


protected virtual void ConfigureMapping(IServiceCollection services)
        {
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.FullName.StartsWith("Microsoft.VisualStudio.TraceDataCollector")));
        }

错误

Missing type map configuration or unsupported mapping.

Mapping types:
HdsBudgetSummary -> ProjectBudgetSummaryViewModel
ProjectPerformanceReview.DomainModel.ComplexDomainModel.Hds.HdsBudgetSummary -> ProjectPerformanceReview.WebApi.ViewModels.BudgetSummary.ProjectBudgetSummaryViewModel

我关注的一些链接 Mapping Lists using Automapper

Automapper 8 mapping not working properly

1 个答案:

答案 0 :(得分:2)

您的个人资料仅从ProjectBudgetSummaryViewModel映射到HdsBudgetSummary。如果您还希望它朝相反的方向映射,则必须扩展轮廓。

public ProjectBudgetSummaryProfile()
{
   CreateMap<ProjectBudgetSummaryViewModel, HdsBudgetSummary>()
      ReverseMap();
   CreateMap<ProjectBudgetSummaryViewModel, CdsBudgetSummary>()
      ReverseMap();
}

仅供参考:您无需从IServiceProvider代表处返回ConfigureServices