I have this class and when OnGet is called, it throws an exception when getting from the DB.
Code:
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);
}
}
Exception:
Can anyone help me understand the root cause of this problem?
Regards
CodePudding user response:
The query as written is attempting to filter results after a projection. Additionally, the projected type (FileUploadModel) does not have the Id field populated so it would have always been the default value (0 if it is an int). If you filter first and then project it should work.
var file = await context.FileUploads
.Where(x => x.Id == Id)
.Select(x => new FileUploadModel
{
FileName = x.FileName,
FileContent = x.FileContent
})
.SingleAsync();