如何从一组行匹配条件中获取不同的值

How to get distinct values from set of rows matching condition

我有table随性。

+----+-----------+-----------+------+---------+------+
| Id | AccountId | ProjectId | Year | Quarter | Data |
+----+-----------+-----------+------+---------+------+
| 39 |       163 |        60 | 2019 |       2 |    0 |
| 40 |       163 |        60 | 2019 |       2 |    8 |
| 41 |       163 |        61 | 2019 |       2 |    1 |
| 42 |       163 |        61 | 2019 |       2 |    2 |
+----+-----------+-----------+------+---------+------+

我想使用 Entity Framework 将 ProjectIds 区分为 Json,目前我的代码如下所示。

    // GET: api/Insight/163/2019/2
    [HttpGet("{accid}/{year}/{qurter}")]
    public async Task<IActionResult> GetSurveys([FromRoute] long accid, [FromRoute] long year, [FromRoute] long qurter)
    {
        //This code gives me the error.
        return await _context.CustomerSatisfactionResults.Select(x=>x.ProjectId)
            .Where(x => x.AccountId == accid && x.Year == year && x.Quarter == qurter).ToListAsync();
    }

当我用参数点击这个端点时,/163/2019/2 我想要一个 Json 响应,

[
  "60", "61"
]

但是我收到以下错误。 我做错了什么?

出现错误的原因是您将 Where 条件应用于仅包含 ProjectId 的投影序列。您应该在 Select 之前使用 Where

要获取不同的值,请使用 Enumerable.Distinct 方法:

return await _context.CustomerSatisfactionResults
   .Where(x => x.AccountId == accid && x.Year == year && x.Quarter == qurter)
   .Select(x => x.ProjectId)
   .Distinct()
   .ToListAsync();