Reputation: 736
I am making a call to a repository which wraps EF core, messing about with the contoso example
public async void PopulateFacultySL( object selectedFaculty )
{
var data = await GetUnitOfWork().Faculties.GetAllAsync();
FacultySL = new SelectList( data, "Id", "Name", selectedFaculty );
}
When refreshing the page, sometimes the dropdown list is populated, sometimes it is not. I am late on the tech (Async and await) and trying to learn, I know it is likely to be something silly somewhere and hoping an experienced eye can see what the issue is.
protected DbSet<TEntity> TypedContext => Context.Set<TEntity>();
public virtual Task<List<TEntity>> GetAllAsync()
{
return ReturnAndFilterByInstitutionAsync( TypedContext.AsQueryable() );
}
public Task<List<TEntity>> ReturnAndFilterByInstitutionAsync( IQueryable<TEntity> query )
{
return query.Where( q => q.InstitutionId == InstitutionId ).ToListAsync();
}
Please let me know if you need to see any other class info
Edit: This is the original calling method from the page
public IActionResult OnGet()
{
PopulateFacultySL(null);
return Page();
}
This then had to change to:
public async Task<IActionResult> OnGet()
{
FacultySL = await GetFacultySL( null );
return Page();
}
to make it accept the await
keyword with the revised GetFacultySL
from the suggestion below
Upvotes: 2
Views: 415
Reputation: 247591
Avoid async void
fire and forget methods.
Reference Async/Await - Best Practices in Asynchronous Programming
Chances are that when PopulateFacultySL
is invoked there are times when it is not completing in time to be included in the response before it is sent to the client. Which is why sometimes it is populated and sometimes it is not when the page is refreshed because they are being invoked in parallel.
What you need to do is refactor the method so that it can be awaited.
public async Task PopulateFacultySL(object selectedFaculty = null) {
var data = await GetUnitOfWork().Faculties.GetAllAsync();
FacultySL = SelectList(data, "Id", "Name", selectedFaculty);
}
and await it on page load
public async Task<IActionResult> OnGetAsync() {
await PopulateFacultySL();
return Page();
}
Now the page will wait for the data to be populated before displaying the page.
Reference Introduction to Razor Pages in ASP.NET Core
Upvotes: 7