[英]Entity Framework Core Joining Related Table
I have an MVC app with Entity Framework Core. 我有一个带有Entity Framework Core的MVC应用程序。 It doesn't work when I run it (I could have swore it worked before), but it works about half the time when debugging.
当我运行它时,它不起作用(我可能曾经发誓它曾经起作用过),但在调试时,它的工作时间约为一半。 What did I do wrong with setting up my Models and whatnot?
设置我的模型有什么问题,什么没做? I followed a little step by step guide, but now I can't find it.
我按照循序渐进的指南进行操作,但现在找不到了。 Sorry if this is a duplicate, I couldn't find the right search keywords to find something similar.
抱歉,如果重复的话,我找不到正确的搜索关键字来查找类似内容。
Models/BaseProduct.cs 型号/BaseProduct.cs
public abstract class BaseProduct
{
public int Id { get; set; }
public string Brand { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Model { get; set; }
[Display(Name = "Main Image")]
public virtual FileDetails MainImage { get; set; }
public virtual FileDetails AdditionalImages { get; set; }
public virtual FileDetails Downloads { get; set; }
}
Models/FileDetails.cs 型号/FileDetails.cs
public class FileDetails
{
public int Id { get; set; }
public string FileName { get; set; }
public string FileDir { get; set; }
public string FileText { get; set; }
}
Controllers/CompressorController.cs 控制器/CompressorController.cs
public async Task<IActionResult> Index()
{
var list = await _context.Compressor.ToListAsync();
foreach (var compressor in list)
{
if (compressor.MainImage == null)
{
FileDetails img = new FileDetails(){FileDir = "", FileName = "NoImage.png", FileText = ""};
compressor.MainImage = img;
}
}
return View(list);
}
So sometimes it does a join on the FileDetails table and sometimes it doesn't. 因此,有时它在FileDetails表上执行联接,有时却不执行。 The Compressor table (that inherits BaseProduct) has the IDs of the FileDetails table, so it seems like I didn't screw up too much.
Compressor表(继承了BaseProduct)具有FileDetails表的ID,因此似乎我没有花太多时间。
Solved: 解决了:
Issue appears to be with Rider. 问题似乎出在Rider身上。 Ran code in Visual Studio and is consistently working with it.
在Visual Studio中运行代码,并一直在使用它。
I couldn't figure out how it applies join sometimes and sometimes not but I am pretty sure that EF Core current version doesn't support Lazy Loading. 我无法弄清楚它有时如何应用联接,有时甚至不联接,但是我很确定EF Core当前版本不支持延迟加载。 So, try eager loading;
因此,请尝试加载。
var list = await _context.Compressor
.Include(x => x.MainImage)
.ThenInclude(x => x.AdditionalImages)
.ThenInclude(x => x.Downloads).ToListAsync();
I modified my code similar to Rainman's suggestion, but that still wasn't working. 我修改了代码,类似于Rainman的建议,但是仍然无法正常工作。
var list = await _context.Compressor
.Include(x => x.MainImage)
.Include(x => x.AdditionalImages)
.Include(x => x.Downloads).ToListAsync();
I ran the code with Visual Studio instead of Rider and it seems to be working pretty consistently. 我使用Visual Studio而不是Rider来运行代码,并且看起来运行得非常一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.