我有一个SQL
表,
╔════╦════════════════════════════════╦═════════╦══════════╗
║ Id ║ Date ║ Col3 ║ Col4 ║
╠════╬════════════════════════════════╬═════════╬══════════╣
║ 1 ║ 2018-10-30 00:00:00.0000000 ║ ....... ║ ........ ║
║ 2 ║ 2018-10-31 00:00:00.0000000 ║ ....... ║ ........ ║
║ 3 ║ 2018-10-30 00:00:00.0000000 ║ ....... ║ ........ ║
║ 4 ║ 2018-10-31 00:00:00.0000000 ║ ....... ║ ........ ║
║ 5 ║ 2018-11-01 00:00:00.0000000 ║ ....... ║ ........ ║
╚════╩════════════════════════════════╩═════════╩══════════╝
我想选择这些行,以便我指定开始日期和结束日期,并且如果我将开始日期设为2018-10-31,并将结束日期设为2018-10-30,则响应的格式如下,
+----+--------------------------------+---------+----------+
| Id | Date | Col3 | Col4 |
+----+--------------------------------+---------+----------+
| 1 | 2018-10-30 00:00:00.0000000 | ....... | ........ |
| 2 | 2018-10-31 00:00:00.0000000 | ....... | ........ |
| 3 | 2018-10-30 00:00:00.0000000 | ....... | ........ |
| 4 | 2018-10-31 00:00:00.0000000 | ....... | ........ |
+----+--------------------------------+---------+----------+
我尝试使用以下内容,但未返回任何内容。我不知道我的查询是否错误。
[HttpGet("GetClamped")]
public async Task<IActionResult> GetIntegration([FromQuery] string start, [FromQuery] string end)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
DateTime startDate = DateTime.ParseExact(start, "yyyy-mm-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact(start, "yyyy-mm-dd", System.Globalization.CultureInfo.InvariantCulture);
var integration = await _context.Integrations.FirstOrDefaultAsync(t => t.Date > startDate && t.Date < endDate);
if (integration == null)
{
return NotFound();
}
return Ok(integration);
}
如果我要将相似的日期分组在一起,该怎么办? 例如:
+----+--------------------------------+---------+----------+
| Id | Date | Col3 | Col4 |
+----+--------------------------------+---------+----------+
| 1 | 2018-10-30 00:00:00.0000000 | ....... | ........ |
| 3 | 2018-10-30 00:00:00.0000000 | ....... | ........ |
| 2 | 2018-10-31 00:00:00.0000000 | ....... | ........ |
| 4 | 2018-10-31 00:00:00.0000000 | ....... | ........ |
+----+--------------------------------+---------+----------+
谢谢。
答案 0 :(得分:1)
为什么您会收到404错误,即:
var integration = _context.Integrations.ToList();
要获取一系列项目,您不能使用FirstOrDefaultAsync
函数。为此,请使用Where
为了对元素进行分组-还有另一个功能GroupBy
。您可以在这里找到更多功能:https://msdn.microsoft.com/en-us/library/system.data.entity.queryableextensions(v=vs.113).aspx
答案 1 :(得分:0)
查询您的数据库
_context.Integrations.FindAll(t => t.Date > startDate && t.Date < endDate).OrderBy(t => t.Date);
希望有帮助!