【发布时间】:2022-01-20 06:25:08
【问题描述】:
我想返回一个复合/嵌套 DTO SearchDto,其中包括 Status(timeMs, resultsFound) 和 List<SearchResult>。
JSON DTO 示例
{
status: {
timeMs: 0.038583,
found: 728,
},
results: [
{
id: "c00f9c89-0683-4818-9043-0df10704f7dc",
score: "32.03388",
fields: {
id: "f42d2a0d-3a30-4cb6-940f-fb474b82588b",
type: "client",
title: "Business Pty Ltd",
description: "Client from Australia",
status: "Active",
url: "#client/f42d2a0d-3a30-4cb6-940f-fb474b82588b"
}
}
]}
SearchDto.cs
// The Search Result Data Transfer Object
public record SearchDto(SearchStatusDto status, IEnumerable<SearchResultDto> results);
// Status contains metadata about the search
public record SearchStatusDto(double timeMs, int found);
// Each Search Result has a unique ID and relevancy score; then contains the payload containing the result
public record SearchResultDto(Guid id, double score, SearchResultFieldsDto fields);
// Actual search data that gets displayed
public record SearchResultFieldsDto(Guid id, string type, string title, string description, string status, string url);
GetSearchResultsQueryHandler.cs
public async Task<SearchDto> Handle(GetSearchResultsQuery request, CancellationToken cancellationToken)
{
// Getsome data from the Search Results Entity.
var items = await context.SearchResult.AsNoTracking().ToListAsync();
// Map it to the Search Result Dto.
var results = mapper.Map<IEnumerable<SearchResultDto>>(items);
// Create the status object with example data.
var SearchStatusDto status = new SearchStatusDto(0.00383, 500);
// Amalgamate the status and List<Result> and return. (not implemented)
return results;
}
问题
我遇到的问题是:
The name 'status' does not exist in the current context [OrganisationName.Services.Api]csharp(CS0103)
我对 C#、.Net 和 MediatR 还很陌生,所以我不确定我是否正确地解决了这个问题。像这样使用 MediatR 是否可能/可取?
【问题讨论】:
-
var object status?是哪个? -
抱歉,我只是在尝试看看这是否可行。应该是
var SearchStatusDto status。 -
产生错误的原因是什么?不要认为它来自您提供给我们的任何代码
-
我不确定,但我对 C# 还很陌生,没有意识到我需要使用
new关键字构建对象然后返回它。我使用以下代码修复了它:-stackoverflow.com/a/70764258/2334389
标签: c# automapper dto cqrs mediatr