【问题标题】:Return distinct collection attribute on AspNet Core API在 AspNet Core API 上返回不同的集合属性
【发布时间】:2021-11-10 19:47:22
【问题描述】:

我是 Asp.Net Core 的新手,我正在尝试构建一个 API。我有以下型号:

public class Location
{
    public string Country { get; set; }
    public string City { get; set; }
    public string Street { get; set; }
}

我已经填充了我的数据库,并且一个国家有多个城市,而该城市有多个街道。 我创建了一个端点来从数据库中返回所有国家:

[HttpGet("countries")]
    public async Task<ActionResult<IEnumerable<string>>> GetCountries()
    {
        return await _context.Location.Select(x=>x.Country).Distinct().ToListAsync();
    }

这是返回字符串数组,我希望它返回以下 JSON 格式的响应:

[
    {"country": "country1"},
    {"country": "country2"},
    ..........
    {"country": "countryN"}
]

我的第二个终点是检索特定国家/地区的所有城市:

 [HttpGet("cities/{country}")]
    public async Task<ActionResult<IEnumerable<string>>> GetCites(string country)
    {
        --------- Missing code ------
    }

我尝试了不同的选项,但我只设法为两个端点获取字符串数组。我尝试用 IEnumerable 替换 IEnumerable,但没有结果。

【问题讨论】:

  • 您在第二个 API 中寻找什么响应格式?和第一个 API 类似吗?

标签: linq asp.net-core entity-framework-core


【解决方案1】:

对于第一个api,创建一个模型:

public class CountryResponse
{
    public string Country { get; set; }
}

并在API的返回类型中使用这个模型类,返回结果为:

[HttpGet("countries")]
public async Task<ActionResult<IEnumerable<CountryResponse>>> GetCountries()
{
     return await _context.Location.Select(x => new CountryResponse{ Country = x.Country }).Distinct().ToListAsync();
}

对于第二个 API 类似,创建响应模型:

public class CityResponse
{
   public string City { get; set; }
}

API 看起来像

[HttpGet("cities/{country}")]
public async Task<ActionResult<IEnumerable<CityResponse>>> GetCites(string country)
{
    return await _context.Location.Where(x => x.Country == country).Select(x => new CityResponse { City = x.City }).ToListAsync();
}

【讨论】:

  • 非常感谢,我有这种使用 DTO 几乎功能的方法,但我使用了错误的 lambda 链。
【解决方案2】:

线

_context.Location.Select(x=>x.Country).Distinct().ToListAsync()

返回一个字符串列表,这就是 ActionResult 将返回的内容。将其转换为所需格式的最简单方法是返回 KeyValuePair。如果您将返回更改为此,它应该可以工作。

return await _context.Location.Select.Distinct().Select(country => new KeyValuePair<string, string>("country", country)).ToList()

与城市的想法相同,只需将它们放入 KeyValuePair 中,您就会得到所需的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多