Search code examples
blazordevexpressblazor-server-sidedevexpress-blazor

How can I create an IEnumerable from Entity Framework async?


I have an extension method that creates an expression to return a set of rows in the database:

public static class SkillsExtensions
{
    public static IEnumerable<Skill> AllSkills(this LouisHoweDbContext context)
    {
        return context.Skills.OrderBy(s => s.Name);
    }
}

The code above does not touch the database (yet) and therefore it is not declared async - correct?

I now use this is a Blazor (server side .NET 7) app. I am using DevExpress controls.

<DxFormLayoutItem Caption="Your skills:" Field="@nameof(RegisterPageModel.Skills)" ColSpanMd="6">
    <DxTagBox Data="@NoTrackingDbContext.AllSkills()"
              TextFieldName="@nameof(Skill.Name)"
              @bind-Values="@RegisterPageModel.Skills"/>
</DxFormLayoutItem>

The above is the Blazor page and therefore I believe it is able to properly handle async methods. But I have no control over this as I pass the method to the DevExpress component.

Is there a way I can force this to be async? And if so, should I? Or is this a case where there is no advantage to async calls?


Solution

  • Use async to get the values, Data expects an IEnumerable

     <DxTagBox Data="@allSkills" ... />
    
      private IEnumerable<Skill> allSkills = default!;
      overide OnInitializedAsync()
      {
        allSkills = await NoTrackingDbContext.AllSkills();
      }
    

    and

        public static Task<IEnumerable<Skill>> AllSkills(this LouisHoweDbContext context)
        {
            return context.Skills.OrderBy(s => s.Name).ToListAsync();
        }
    

    Although i doubt the use of an extension method here, make it a member of an injectable service (repository).