c# - Mapster.Tool 使用 codegen 生成映射器而不是 DTO

标签 c# mapster

我可以使用 Mapster.Tool 生成映射器而不生成我要映射到的类吗?我有一个典型的域对象进出 DTO 场景,但示例代码在这里

https://github.com/MapsterMapper/Mapster/tree/master/src/Sample.CodeGen

和这里的文档

https://github.com/MapsterMapper/Mapster/wiki/Mapster.Tool

两者都专注于从域对象生成 DTO,方法是使用属性对其进行注释或使用配置。有创建特定于 CRU 的 DTO 的配置,但我仍然宁愿创建我自己的 DTO,但不必创建我自己的映射。

最佳答案

是的,您可以 - 查看记录的基于接口(interface)的代码生成 here .

这允许您定义一个接口(interface),该接口(interface)将根据现有类生成映射器。

您可以从那里选择如何使用生成的映射器。在服务中注册,然后使用 DI 作为一种方式。

这是一个简单的例子:

    [Mapper]
    public interface IContactMapper
    {
        ContactDetailVm MapTo(Contact contact);
    }

会导致

    public partial class ContactMapper : IContactMapper
    {
        public ContactDetailVm MapTo(Contact p2)
        {
            return p2 == null ? null : new ContactDetailVm()
            {
                Id = p2.Id,
                Created = p2.Created,
                LastUpdate = p2.LastUpdate,
                Title = p2.Title,
                FirstName = p2.FirstName,
                LastName = p2.LastName,
                PreferredName = p2.PreferredName,
                BirthYear = p2.BirthYear
            };
        }
    }

不过,我认为您无法使用该工具为现有实体生成映射扩展方法。至少我不知道它可以在 v6 中完成。

关于c# - Mapster.Tool 使用 codegen 生成映射器而不是 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66574520/

相关文章:

c# - 反序列化从 SQL 查询返回的 XML 对象?

c# - 在 C# 中将匿名类型转换为列表

c# - 如何通过 iPhone/iPad 检测 css 样式

c# - Crystal Reports 代码契约(Contract)冲突

c# - 使用 Mapster 将一个类属性映射到两个不同的类属性

c# - 数据迁移 MS SQL - C# 中的 MySQL

c# - 通过 Autofac 进行 Mapster 依赖注入(inject)

blazor - Mapster 和 Blazor

c# - Mapster Adpat 不工作