使用Mapster Mapper时,我觉得重复不应该使用的代码.
public class Workshop
{
public Guid Id {get;set;}
public string? Title {get;set;}
public string? Text {get;set;}
public IList<WorkshopParticipant> WorkshopParticipants {get;set;}
}
public class WorkshopDto
{
public Guid Id {get;set;}
public string? Title {get;set;}
public int Participants {get;set;}
}
public class WorkshopWithTextDto : WorkshopDto
{
public string? Text {get;set;}
}
TypeAdapterConfig<Workshop, WorkshopDto>.NewConfig()
.Map(dest => dest.Participants, src => src.Participants!.Count(x => x.Status == "attended")))
// Why should I have this, when WorkshopWithTextDto is inheriting from WorkshopDto that already have the mapping?
TypeAdapterConfig<Workshop, WorkshopWithTextDto>.NewConfig()
.Map(dest => dest.Participants, src => src.Participants!.Count(x => x.Status == "attended")))
有没有什么方法可以重复使用映射,这样我就不必重复计算参与者了?
从其他问题中,我看到可以对源对象使用元组,但在目标对象上似乎不可能--或者我错了?
统计参与人数的例子只是为了描述这个问题.通常情况下,计算要复杂得多,如果只需要维护一个位置就好了.
一种解决方案是使用一个函数为目的地赋值,如下所示:
public static int CountParticipants(IList<WorkshopParticipant> workshopParticipants)
{
return workshopParticipants!.Count(x => x.Status == "attended");
}
TypeAdapterConfig<Workshop, WorkshopDto>.NewConfig()
.Map(dest => dest.Participants, src => CountParticipants(src.WorkshopParticipants!))
TypeAdapterConfig<Workshop, WorkshopWithTextDto>.NewConfig()
.Map(dest => dest.Participants, src => CountParticipants(src.WorkshopParticipants!))
但我仍然需要执行两个TypeAdapterConfigs.
这是否可以做到"更智能"--更易于维护?