我有這個類,當呼叫 OnGet 時,它在從資料庫獲取時拋出例外。
代碼:
public class DownloadsModel : PageModel
{
[BindProperty(SupportsGet = true)]
public int Id { get; set; }
[BindProperty(SupportsGet = true)]
public string FileType { get; set; }
private readonly IDbContextFactory<ApplicationDbContext> _dbFactory;
public DownloadsModel(IDbContextFactory<ApplicationDbContext> dbFactory)
{
_dbFactory = dbFactory;
}
public async Task<IActionResult> OnGet()
{
var context = _dbFactory.CreateDbContext();
var file = await context.FileUploads.Select(x => new FileUploadModel
{
FileName = x.FileName,
FileContent = x.FileContent
}).SingleAsync(x => x.Id == Id);
return File(file.FileContent, FilesConst.DownloadsConst.ApplicationForceDownload, file.FileName);
}
}
例外:

誰能幫我理解這個問題的根本原因?
問候
uj5u.com熱心網友回復:
所寫的查詢試圖在投影后過濾結果。此外,投影型別 (FileUploadModel) 沒有填充 Id 欄位,因此它始終是默認值(如果是 int,則為 0)。如果您先過濾然后投影它應該可以作業。
var file = await context.FileUploads
.Where(x => x.Id == Id)
.Select(x => new FileUploadModel
{
FileName = x.FileName,
FileContent = x.FileContent
})
.SingleAsync();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318205.html
上一篇:Chartjs背景色多個資料集
下一篇:基于給定條件的LINQ過濾器串列
