【发布时间】:2021-09-15 18:15:28
【问题描述】:
我有一个响应模型。在模型中,我需要从 JSON 文件加载查询。例如,我从 const 加载 json 数据。在实体(Problem)属性中Queries是不需要的,所以不存在。
这是模型:
public class ProblemModel
{
public int Id { get; set; }
public bool IsResolved { get; set; }
public ICollection<QueryModel> Queries{ get; set; }
public int State {get; set; }
}
这是QueryModel:
public class QueryModel
{
public string Query { get; set; }
public QueryModel[] Accept { get; set; }
public QueryModel[] No { get; set; }
}
这是 Automapper 配置文件
public class ProblemMappingProfile : Profile
{
public ProblemMappingProfile()
{
const string jsonData = @"[
{
'Query': 'Query1',
'Accept': [
{
'Query': 'Query1_1',
'Accept': [
{ }
],
'Reject': [
{ }
]
}
],
'Reject': [
{
'Query': 'Query1_2',
'Accept': [
{ }
],
'Reject': [
{ }
]
}
]
}
]";
QueryModel[] json = JsonSerializer.Deserialize<QueryModel[]>(jsonData.Replace('\'', '\"'));
CreateMap<Problem, ProblemModel>()
.ForMember(d => d.Queries, o => o.MapFrom(s => json))
.ReverseMap()
}
}
每次映射ProblemModel 时,我都需要加载查询。例如:
return _mapper.Map<ProblemModel>(await _context.Problems.Where(x => x.Id == id).FirstOrDefaultAsync());
或
return _mapper.Map<ProblemModel>(await _context.Problems.Where(x => x.state == 2).ToListAsync());
我尝试在 automapper 配置文件中映射 Queries,但这是错误的。因为配置文件构造函数工作一次。构建自动映射配置文件后出现错误
执行请求时发生未处理的异常。
System.ArgumentException:字段“SimplyQuery.Services.Models.ProblemMappingProfile+c__DisplayClass0_0.json”没有为类型“SimplyQuery.Data.Entities.Problem”定义
所以我无法理解:
-
我需要在哪里映射 json 数据以将其动态包含到结果模型中?我该怎么做?
-
为什么在构造函数中出现错误? JSON数据反序列化得很好,所以数组必须分配给另一个数组,不是吗?
【问题讨论】:
-
您应该为您的 json 数据创建一个类 (dto) 并将该 DTO 类映射到实际实体。
-
QuerryModel 是 DTO 类。对于来自 db 的实体,我不需要这个查询。创建响应时,它是 DTO 中的附加数据。
-
看起来你可以通过在代码中手动执行来更快:)
标签: c# json .net .net-core automapper