提问人:Davrozz 提问时间:9/17/2022 最后编辑:marc_sDavrozz 更新时间:9/18/2022 访问量:454
ASP.NET Entity Framework InMemory 数据库未保存相关子实体
ASP.NET Entity Framework InMemory database not saving related sub-entities
问:
我有一个 ASP.NET 项目,我尝试使用内存数据库来保存天气对象。
该类包含另一个对象 。在应用程序启动时,我生成数据并将其保存到我的数据库上下文中。但是,在发送 get 请求时,除 location 之外的所有天气属性都有效,该值每次都为 null。Weather
Location
相关代码:
天气
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();
}
我已经尝试了多种解决方案。但无论我做什么,子实体 () 都保持 null:Location
答:
0赞
Davrozz
9/18/2022
#1
感谢评论中的帮助,我找到了适合我的方法:
将此方法添加到我的类中解决了无法加载的问题: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();
}
评论
OnModelCreating
Include
return _context.Weathers.Include(...).ToList();
Include