使用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.

这是否可以做到"更智能"--更易于维护?

推荐答案

请看我在你的问题下面的 comments .此外,根据Mapster documentation,您可以将派生类型包括到基于类型声明中,以便它复制其设置:

TypeAdapterConfig<Vehicle, VehicleDto>.NewConfig()
    .Include<Car, CarDto>();

Vehicle vehicle = new Car { Id = 1, Name = "Car", Make = "Toyota" };
var dto = vehicle.Adapt<Vehicle, VehicleDto>();

dto.ShouldBeOfType<CarDto>();
((CarDto)dto).Make.ShouldBe("Toyota"); //The 'Make' property doesn't exist in Vehicle

Csharp相关问答推荐

为什么xslWriter不总是按照xslWriterSet中指定的格式格式化该文档?

注册通用工厂的C# Dep注入

Monty Hall游戏节目模拟给我50/50的结果

将委托传递到serviceccollection c#web API

读取配置文件(mytest. exe. config)

C#中使用BouncyCastle计算CMac

安装附加的. exe与Visual Studio

C++/C#HostFXR通过std::tuple传递参数

MAUI查询参数单一字符串项将不起作用

创建临时Collection 最有效的方法是什么?堆栈分配和集合表达式之间的区别?

如何在NET 8最小API中自动记录TypedResults.Stream响应

try 链接被委派者(多播委托)时,无法将获取运算符应用于类型为';方法组&39;和方法组';的操作数

多个选项卡上的MudForm验证

如何在Polly重试策略成功之前将HttpClient请求排队?

如何在.NET Core 8中自定义标识用户模型

SharpZipLib在文件名前加上目录名,生成tar.gz

C#;AvaloniaUI;MVVM;当另一个窗口上的按钮被单击时,如何更新视图图像源?

有没有更好的方法来使用LINQ获取整行的计算组

如何在.NET8中使用Blazor Web App(WebAssembly)托管服务器端控制器?

分别切换用于读取和写入的EF核心日志(log)