【问题标题】:AutoMapper recognize prefixes with dependency injectionAutoMapper 通过依赖注入识别前缀
【发布时间】:2021-03-25 13:06:03
【问题描述】:

我安装了 AutoMapper.Extensions.Microsoft.DependencyInjection nuget 包,并且我使用的是 .NET Core 3.1。根据文档 (https://docs.automapper.org/en/stable/Configuration.html),我应该能够为我的属性名称添加前缀。但是当我映射我的两个类时,带有前缀的属性为空。我有一个具有多个属性的抽象类,这些属性扩展到我的 UserDto 模型然后我将 UserDto 模型映射到没有抽象类的 UserEntity 模型。我的 UserEntity 模型对每个属性都使用前缀 User,例如UserId、UserName,而我的 UserDto 只使用 Id、Name 等。我注册 AutoMapper 并添加我的配置如下:

        #region Auto Mapper
        services.AddAutoMapper(config =>
        {
            config.RecognizePrefixes(new[] { "User", "Role", "Language" });
            config.AddProfile(new DtoToEntityProfile());
            config.AddProfile(new ContractToDtoProfile());

        }, typeof(Startup));
        #endregion

我将我的个人资料添加到配置中,看看这是否可行。在 Automapper 还可以通过扫描程序集自动找到我的配置文件之前。在不手动映射每个属性的情况下,我需要做什么才能将我的 Dto 映射到我的实体模型?

【问题讨论】:

    标签: c# dependency-injection automapper


    【解决方案1】:

    通过查看 Auto Mapper 的 Profile 类中的函数和属性,我发现有一个 RecognizePrefixes 和一个 RecognizeDestinationPrefixes 函数,RecognizePrefixes 函数仅从源中删除前缀,RecognizeDestinationPrefixes 函数仅从目标中删除前缀。

    RecognizePrefixes 是一个误导性的名称。我通过如下实现配置解决了我的问题:

            #region Auto Mapper
            services.AddAutoMapper(config =>
            {
                config.RecognizeDestinationPrefixes(new[] { "User", "Role", "Domain", "Language" });
                config.RecognizePrefixes(new[] { "User", "Role", "Domain", "Language" });
    
            }, typeof(Startup));
            #endregion
    

    【讨论】:

      猜你喜欢
      • 2011-05-11
      • 2011-04-06
      • 2023-03-12
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多