使用.m核心自动映射器将List <Class>映射到List <Class>

时间:2019-10-28 11:16:57

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

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

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为false,我想从Push模型列表中获取Sent模型列表。

所以我有以下代码:

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

但是failedPushes为空。要注入映射器,我需要使用IMapper界面:

// class prop 
private readonly IMapper _mapper;

... 

// constructor 

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

Startup.cs类中,我有以下内容:

services.AddAutoMapper(typeof(Startup));

那怎么了?

1 个答案:

答案 0 :(得分:1)

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

Automapper将自动搜索继承Profile的类以创建配置。

创建一个文件夹Profile,并将您的配置放在此处。

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