I'm working in VS 2022 .net7 with sql server 2019 and Razor pages. I'm using the ASP.Net Core Web App template. I used scaffolding to generate starter pages for database access - and that worked very well.
This scaffold code provided the basic data for my index page.
This is the scaffold code:
public IList<myPosts> myPosts { get;set; } = default!;
public async Task OnGetAsync()
{
if (_context.myPosts != null)
{
myPosts = await _context.myPosts.ToListAsync();
}
}
However, I need to filter the data. And this is most of the code I need to filter the data:
namespace someBlog.Pages
{
public class FAQlistModel : PageModel
{
private readonly someBlog.Data.someBlogContext _context;
public FAQlistModel(someBlog.Data.someBlogContext context)
{
_context = context;
}
public IList<myPosts> myPosts { get;set; } = default!;
public async Task OnGetAsync()
{
if (_context.myPosts != null)
{
var myposts = (from x in _context.myPosts
where x.IsApproved == "FAQ"
orderby x.PublishDate
select new myPosts
{
Id = x.Id,
Title = x.Title,
Summary = x.Summary,
Content = x.Content.Substring(0, 200),
/*more fields*/
}).ToList();
myPosts = myposts;
}
}
}
}
This does provide the selected records with the data formated correctly. However, I get this warning "Warning CS1998 This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await....."
Although I don't know much about async coding protocols, I'd like to stay with the async code as generated by scaffolding - And, I don't need much database interaction beyond what scaffolding provides.
I'm looking for a way to fix my code so it runs asynchronous. Although this code doesn't work, this is essentially what I'd like to do:
myPosts = await myposts;
Everything I've tried so far just produces errors. Thanks
If you wanna use async code in your code, you can try to change your code like:
public IList<myPosts> myPosts { get;set; } = default!;
public async Task OnGetAsync()
{
if (_context.myPosts != null)
{
var myposts = await _context.myPosts.Where(x => x.IsApproved == "FAQ").OrderBy(x => x.PublishDate).Select(x => new myPosts { Id = x.Id, Title = x.Title, Summary =x.Summary, Content = x.Content.Substring(0, 200) }).ToListAsync();
myPosts = myposts;
}
}