【问题标题】:AutoMapper with nested objects and container class具有嵌套对象和容器类的 AutoMapper
【发布时间】:2021-10-01 20:07:46
【问题描述】:

我正在开发一个带有 .NET 核心并使用 AutoMapper 的 API。

所有 API 响应都将使用 JSON 响应中的数据元素进行包装,如下例所示

获取用户

{
  "data" {
       "id" : 1,
       "user_name": "abc"
       "countryr" : {
         "id" : 1348,
         "code" : "USA"
        } 
   }
}

所以我们有一个UserCountry 的实体

  public partial class User
    {

        public int Id { get; set; }
        public string FirstName { get; set; }

        public virtual Country country { get; set; }

    }  

  public partial class Country
    {
        public int Id { get; set; }
        public string Code{ get; set; }
    }

要将实体映射到 DTO,我们有以下响应 DTO

 public class GetUserDTO {
      public User data {get; set;} // To wrap reponse with data
    }

 public class UserDto {
    public int id {get; set;}
    public String user_name {get; set;}
    public Country country {get; set;}
    }

 public class CountryDto  {
    public int id {get; set;}
    public String code {get; set;}
   }

根据我的理解,我应该将实体 User 映射到 UserDTO 并将 Country 实体映射到 CountryDTO 但是 GetUserDTO 类本身呢?它基本上包含其他实体,因此类本身不能映射到它充当容器的任何东西。

所以低于我到目前为止所做的不正确

public class UserProfile : AutoMapper.Profile
{
    public MappingProfile()
    {

        CreateMap<User, GetUserDTO>();
        CreateMap<User, UserDto>()
        .ForMember(userDto => userDto.user_name, map => map.MapFrom(user => user.FirstName))
        CreateMap<Country, CountryDto>();


    }
}

Json 响应

{
  "data" : null
}

遇到这种情况该怎么办?

【问题讨论】:

    标签: c# asp.net asp.net-core asp.net-web-api automapper


    【解决方案1】:

    您不应在 DTO 类中引用您的实体类。您可能希望按如下方式更改 DTO。

    public class GetUserDTO {
      public UserDto data {get; set;} // To wrap reponse with data
    }
    public class UserDto {
      public int id {get; set;}
      public string user_name {get; set;}
      public CountryDto country {get; set;}
    } 
    public class CountryDto  {
      public int id {get; set;}
      public string code {get; set;}
    

    }

    然后在 Mapper 配置文件中,您需要显式映射每个属性,因为大小写不同(如果名称完全相同,AutoMapper 将在没有显式映射的情况下进行映射。在您的示例中,存在大小写差异)

    然后从 MapperProfile 中删除以下行,因为没有从 User 类到 GetUserDTO 类的映射。这就是您没有得到任何输出的原因。

    CreateMap<User, GetUserDTO>();
    

    在获取数据时,您应该创建一个新的 GetUserDTO 类实例,并根据用户对象的映射结果设置属性“数据”。

    这将为您提供输出。

    【讨论】:

    • 谢谢!它正在工作。这是一个好习惯吗?或者你有什么建议
    • 如果你在控制器中做映射,那么你真的不需要GetUserDTO类,你可以使用匿名对象来返回数据。如果您从数据访问中返回 GetUserDTO,那么这应该没问题
    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2019-04-13
    相关资源
    最近更新 更多