首页 > 解决方案 > 地图列表列出带有 .net 核心的自动映射器

问题描述

我有两个模型。第一个是:

public class Push
{
    public int PushId { get; set; }
    public Customer Customer { get; set; }
    public int CustomerId { get; set; }
    public string PackageId { get; set; }
    public string Category { get; set; }
    public string Advertiser { get; set; }
    public PushTemplate PushTemplate { get; set; }
    public string TemplateType { get; set; }
    public string IntervalType { get; set; }
    public int TopDateTimeBorder{ get; set; }
    public int  BottomDateTimeBorder { get; set; }
    public DateTime ClientStartDateTime { get; set; }
    public string LangCode { get; set; }
    public string PushTitle { get; set; }
    public string PushBody { get; set; }
    public string FCMResponse { get; set; }
    public bool Sent { get; set; }
    public DateTime CreatedAt { get; set; }
    public Distribution Distribution { get; set; }
    public Push()
    {
        CreatedAt = DateTime.UtcNow;
    }
}

第二个是:

public class FailedPush
{
    public int FailedPushId { get; set; }

    public Customer Customer { get; set; }
    public int CustomerId { get; set; }
    public string PackageId { get; set; }
    public string Category { get; set; }
    public string Advertiser { get; set; }
    public PushTemplate PushTemplate { get; set; }
    public string TemplateType { get; set; }
    public string IntervalType { get; set; }
    public int TopDateTimeBorder{ get; set; }
    public int  BottomDateTimeBorder { get; set; }
    public DateTime ClientStartDateTime { get; set; }
    public string LangCode { get; set; }
    public string PushTitle { get; set; }
    public string PushBody { get; set; }
    public string FCMResponse { get; set; }
    public DateTime CreatedAt { get; set; }
    public Distribution Distribution { get; set; }
    public FailedPush()
    {
        CreatedAt = DateTime.UtcNow;
    }
}

如果属性为假,我想FailedPush从模型列表中获取模型列表。PushSent

所以我有以下代码:

 var failedPushes = _mapper.Map<List<Push>, List<FailedPush>>(await pushes.Where(x => !x.Sent).ToListAsync()); 

但是failedPushes是空的。注入 mapper I 用户IMapper界面:

// class prop 
private readonly IMapper _mapper;

... 

// constructor 

public ScopedProcessingService(IMapper mapper) 
{ 
...
_mapper = mapper;
...
}

Startup.cs课堂上,我有以下内容:

services.AddAutoMapper(typeof(Startup));

那么有什么问题呢?

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

解决方案


您必须创建映射类的配置。

Automapper 会自动搜索继承 Profile 的类来创建配置。

创建一个文件夹 Profile 并将您的配置放在那里。

public class PushProfile : Profile
{
    public PushProfile()
    {
        CreateMap<Push, FailedPush>();
    }
}

推荐阅读