映射列表 到列表 具有用于.net内核的自动映射器

问题描述 投票:0回答:1

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

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));

那么怎么了?

c# asp.net-core-mvc automapper
1个回答
1
投票

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

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

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

public class PushProfile : Profile
{
    public PushProfile()
    {
        CreateMap<Push, FailedPush>();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.