Generally, things will be asynchronous in the controller class. Now I have a service, which has the DbContext through Dependency Injection. This is how it looks like:
public class SomeService : ISomeService
{
private readonly _context;
public SomeService(SomeDbContext context)
{
_context = context;
}
public User SomeFunction(int id)
{
// how to make this async like in the usual controller?
var user = _context.User.Find(id);
var groups = _context.Group.ToList();
return user
}
}
How should I make the function async, like how it’s usually in the controller? Or is it not needed at all?
EDIT: The accepted answer answers the question already. The biggest problem I made, which resulted in this post, was not having using the correct using statement. Don’t forget to add using Microsoft.EntityFrameworkCore; to your file.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
A lot of the standard methods have *Async variants for them. You can use this:
public class SomeService : ISomeService
{
private readonly _context;
public SomeService(SomeDbContext context)
{
_context = context;
}
public async Task<User> SomeFunction(int id)
{
var user = await _context.User.FindAsync(id);
var groups = await _context.Group.ToListAsync();
return user;
}
}
It is a good convention to follow the same naming and also use an Async suffix in your methods, if you plan to support both synchronous and asynchronous versions. Moreover, you don’t necessarily need to await each asynchronous call, if you don’t need to work with the variable. You can just pass the call to the caller of the method, e.g.:
public Task<User> SomeFunction(int id) => _context.User.FindAsync(id);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0