when I try to get the single record into a model using SingleOrDefaultAsync
, it shows an error
List<Model> doesn't contain definition SingleOrDefaultAsync and accessible extension method
public class MemoryRepository
{
private List<Genre> _genres;
public MemoryRepository() //Constructor
{
_genres = new List<Genre>()
{ new Genre(){Id=1,GenreName="Comedy"},
new Genre(){Id=2,GenreName="Action"}
};
}
public async Task<Genre> GetGenreById(int Id)
{
return await _genres.SingleOrDefaultAsync(x => x.Id == Id);
}
}
CodePudding user response:
SingleOrDefaultAsync
and similar ~Async
methods are from Entity Framework Core and can be used to asynchronously query the database. They are used when working with an IQueryable
, which is an abstraction to mean “things that can be queried“.
Lists and other in-memory collections (e.g. arrays) are not queryable, since operations on them happen by working with the collection itself. Instead, they are enumerable, implementing IEnumerable
, which makes them usable with the standard synchronous LINQ methods.
So you can just use the synchronous SingleOrDefault
instead of the asynchronous SingleOrDefaultAsync
here. This also means that you no longer need to await the result and the method can return synchronously as well:
// return type is changed to reflect a synchronous result
public Genre GetGenreById(int Id)
{
return _genres.SingleOrDefault(x => x.Id == Id);
}
If you need your method to still return a Task<Genre>
(e.g. if you need to implement an interface that is meant for asynchronous usage), then you can use Task.Result
to wrap your synchronous result inside a task:
// note that there is no `async` here
public Task<Genre> GetGenreById(int Id)
{
return Task.FromResult(_genres.SingleOrDefault(x => x.Id == Id));
}
CodePudding user response:
You should be using it .SingleOrDefault
Or .FirstOrDefault()
Like below:-
...
return _genres.SingleOrDefault(x => x.Id == Id);
Or
...
return _genres.FirstOrDefault(x => x.Id == Id);
It will resolve your issue.