【发布时间】:2021-10-01 20:07:46
【问题描述】:
我正在开发一个带有 .NET 核心并使用 AutoMapper 的 API。
所有 API 响应都将使用 JSON 响应中的数据元素进行包装,如下例所示
获取用户
{
"data" {
"id" : 1,
"user_name": "abc"
"countryr" : {
"id" : 1348,
"code" : "USA"
}
}
}
所以我们有一个User 和Country 的实体
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