0

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?

H H
  • 263,252
  • 30
  • 330
  • 514
David Thielen
  • 28,723
  • 34
  • 119
  • 193

1 Answers1

0

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).

H H
  • 263,252
  • 30
  • 330
  • 514
  • Thank you and a follow-up question. Why is there no ToEnumerableAsync() call? As to your suggestion about making this injectable, I posted a question and hope to get your reasoning - https://stackoverflow.com/questions/76025233/what-are-the-trade-offs-of-injecting-a-dbcontext-to-call-queries-and-injecting-e thanks – David Thielen Apr 15 '23 at 23:38
  • Also, I think the correct code is: ` public static async Task> AllSkills(this LouisHoweDbContext context) { return await context.Skills.OrderBy(s => s.Name).ToListAsync(); }` – David Thielen Apr 15 '23 at 23:45
  • In a method like this you can "elide async and await", a small saving. – H H Apr 16 '23 at 06:44
  • I'm of the school of being explicit. And granted, that's a stylistic decision that we each do what works best for us. I use () in my boolean expressions so there's no need to remember precedence, I keep the {} for a namespace, and I still declare main(). I figure clarity never hurts. And in the case of the above, it actually can make a difference - https://blog.stephencleary.com/2016/12/eliding-async-await.html Again, thanks for the solution. – David Thielen Apr 16 '23 at 16:08