基于下面的代码,我想将数据库表连接到EF Core 3.1。问题是,ModellNavigation和ManufacturerNavigation返回空值。我做错了什么?请帮我弄一下这个。
public IEnumerable<ViewModel> GetAll()
{
List<ViewModel> models = new List<ViewModel>();
foreach(Detail detail in _context.Detail)
{
ViewModel viewModel = new ViewModel
{
ID = detail.DetailId,
Manufacturer = detail.ModellNavigation.ManufacturerNavigation.Name,
Modell = detail.ModellNavigation.Name,
Consumption = detail.Consumption,
Color = detail.Color,
Year = detail.Year,
Horsepower = detail.Horsepower
};
models.Add(viewModel);
}
return models;
}发布于 2020-09-17 10:25:57
您需要在EntityFramework配置中定义Detail和ModelNavigation的关系,以便在访问detail模型时加载模型导航。请查看此链接:https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key
发布于 2020-09-17 11:47:19
在这段代码中,modell返回null,尽管它使用了lasy加载!再次感谢你的帮助,我真的很感激!(请原谅我的英语,我不是本地人!)
[HttpGet]
public IEnumerable<CarView> getAllCars()
{
List<CarView> carViews = new List<CarView>();
foreach(Manufacturer manufacturer in _context.Manufacturer)
{
CarView car = new CarView();
car.Manufacturer = manufacturer.Name;
foreach(Modell modell in manufacturer.Modell)
{
car.Modell = modell.Name;
foreach(Detail detail in modell.Details)
{
car.ID = detail.DetailId;
car.Consumption = detail.Consumption;
car.Color = detail.Color;
car.Year = detail.Year;
car.Horsepower = detail.Horsepower;
}
}
carViews.Add(car);
}
return carViews;
}发布于 2020-09-18 18:18:29
像您这样的枚举将使每个循环只有一个查询,如果您还添加了延迟加载,则会生成更多的查询和复杂性。
您应该直接在EF Core中投影您的查询,这将只生成一个到数据库的查询。
public IEnumerable<ViewModel> GetAll()
{
return _context.Detail.Select(
d => new ViewModel()
{
ID = detail.DetailId,
Manufacturer = detail.ModellNavigation.ManufacturerNavigation.Name,
Modell = detail.ModellNavigation.Name,
Consumption = detail.Consumption,
Color = detail.Color,
Year = detail.Year,
Horsepower = detail.Horsepower
}
).ToList();
}https://stackoverflow.com/questions/63930315
复制相似问题