1

I'm new here and pretty much new in C# too. I have this code:

[Bind(Direction.ServerToClient)]
public List<AutorListModel> Autors { get; set; }
public override async Task PreRender()
{
   Autors =  await AutorService.GetAllAutorsAsync();
   await base.PreRender();
}

And this:

public async Task<List<AutorListModel>> GetAllAutorsAsync()
{
    using (var dbContext = CreateDbContext())
    {
        return await dbContext.Autors.Select(
            s => new AutorListModel
            {
                Id = s.Id,
                Jmeno = s.Jmeno,
                Prijmeni = s.Prijmeni
            }
            ).ToListAsync();
    }
}

But AutorService.GetAllAutorsAsync();shows this error:

An object reference is required for the non-static field, method, or property 'AutorService.GetAllAutorAsync()'

I know that it is because I want to use async method when static is required, but I don't know what to change. Does anyone have any idea what to do?

kahveci
  • 1,429
  • 9
  • 23
  • 1
    Either make the method/class static or create an `AutorService` object – Daxtron2 Apr 17 '18 at 19:19
  • A method can be static and asyc. – juharr Apr 17 '18 at 19:21
  • 2
    *"I know that it is becose I want to use async method when static is required"* - Those two things have nothing to do with each other. The error is telling you that you need to call that method on an object instance of that class. You're trying to call a non-static method in a static way. If the method is *supposed* to be static, make it static. If it's *not*, you need an instance of the object. – David Apr 17 '18 at 19:22

1 Answers1

0

I noticed this is the WeatherForecastService.cs file in the C# Blazor demo project.

The class is not static but it does not give this error?

There must be some extra way of indicating that a class is static

No, it's this that makes an instance of it in FetchData.razor:

@inject WeatherForecastService ForecastService

Paul McCarthy
  • 818
  • 9
  • 24