我有一个ASP.NET项目,在该项目中我尝试使用内存中的数据库来保存天气对象。
Weather
类包含另一个对象Location
。在应用程序启动时,我生成数据并将其保存到数据库上下文中。然而,当发送get请求时,除了位置之外,所有天气属性都有效,该值每次都为null。
相关代码:
天气
public class Weather
{
public int Id { get; private set; }
public Variable WeatherVariable { get; set; }
public Unit WeatherUnit { get; set; }
public Location WeatherLocation { get; set; }
}
位置
public class Location
{
public int Id { get; private set; }
public long LocationCode { get; set; }
public string LocationName { get; set; }
}
在应用程序启动时,运行以下代码将数据添加到内存数据库中:
using (var context = new WeatherContext(
serviceProvider.GetRequiredService<DbContextOptions<WeatherContext>>()))
{
// Look for any Weather objects.
if (context.Weathers.Any())
{
return; // Data was already seeded
}
string[] weatherLocations = {
"Utrecht", "Amersfoort", "Amsterdam", "Langerak", "Putten", "Rotterdam", "Den Haag", "Aken"
};
context.Weathers.AddRange(
Enumerable.Range(1, 5).Select(index => new Weather
{
WeatherLocation = new Location
{
LocationCode = Random.Shared.Next(1000, 7000),
LocationName = weatherLocations[Random.Shared.Next(weatherLocations.Length)]
},
WeatherUnit = Unit.CELSIUS,
WeatherVariable = Variable.TEMPERATURE
}).ToList());
// I already tried this from a different stackoverflow question, but didn't work for me.
context.Weathers.Include(w => w.WeatherLocation);
context.SaveChanges();
}
然后是控制器:
[HttpGet]
public List<Weather> GetWeathers()
{
_context.Weathers.Include(location => location.WeatherLocation);
return _context.Weathers.ToList();
}
我已经尝试了多种解决方案。但无论我做什么,子实体(Location
(都保持为空:
API响应截图
感谢评论中的帮助,我找到了对我有用的东西:
将此方法添加到我的WeatherContext
类解决了Location
未加载的问题:
// This is so that the Weather objects automatically include location upon loading.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Weather>().Navigation(w => w.WeatherLocation).AutoInclude();
}