问题描述:我正在将ASP.NET Core 2.1与Entity Framework Core一起使用来创建Web API。
我想重写我的Entity Framework查询,以将一个列表作为键的值而不是键/值对的列表输出。
预期结果:
{
"insertedAt": "2019-10-17T17:03:55.813",
"country": "Germany",
"forecastRun": "56F1D5B4-F0EF-11E9-8522-04D3B088DC49",
"origin": "manual",
"id": 68,
"Timeseries": [
{
"timestamp": "2019-10-14T19:00:00", "value": 12
},
{
"timestamp": "2019-10-14T20:00:00", "value": 10
},
{
"timestamp": "2019-10-14T21:00:00", "value": 19
}
]
}
实际结果:
[
{
"value": 0,
"insertedAt": "0001-01-01T00:00:00",
"timestamp": "0001-01-01T00:00:00",
"country": null,
"forecastRun": null,
"origin": null,
"id": 68,
"Timeseries": []
},
{
"value": 0,
"insertedAt": "0001-01-01T00:00:00",
"timestamp": "0001-01-01T00:00:00",
"country": null,
"forecastRun": null,
"origin": null,
"id": 69,
"Timeseries": []
}
...
]
如您所见,它现在不仅可以输出键/值对的预期列表,而且还可以释放所有其他信息。
我尝试过的事情:
Models / ForecastModel.cs
using System;
using System.Collections.Generic;
namespace tradingdata.Models
{
public partial class ModelForecast
{
public int Value { get; set; }
public DateTime InsertedAt { get; set; }
public DateTime Timestamp { get; set; }
public string Country { get; set; }
public string ForecastRun { get; set; }
public string Origin { get; set; }
public int Id { get; set; }
public IEnumerable<Timeseries> MyTimestamps { get; set; }
= new List<Timeseries>();
}
public partial class Timeseries
{
public int Id { get; set; }
public double Value { get; set; }
public DateTime Timestamp { get; set; }
}
}
Controllers / ForecastController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using tradingdata.Models;
namespace tradingdata.Controllers
{
[Route("api/forecasts")]
[ApiController]
public class ForecastController : ControllerBase
{
private readonly tradingdataContext _context;
public ForecastController(tradingdataContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetModelForecast([FromQuery] DateTime from, DateTime to, string model, string country)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var forecasts = await _context.ModelForecast
.Where(m => m.Timestamp >= from && m.Timestamp <= to && m.Country == country)
.ToListAsync();
if (forecasts == null)
{
return NotFound();
}
return Ok(forecasts.Select(x => new ModelForecast
{
Id = x.Id,
MyTimestamps = x.MyTimestamps.Select(z => new Timeseries
{
Id = z.Id
})
})
);
}
}
}
感谢您的帮助。