I found out a way to do it synchronous but I am unable to do it asynchronous.
public async Task<UserModel> GetLastCreatedUser()
{
return _users
.Find(_ => true)
.SortByDescending(u => u.DateCreated)
.Limit(1);
}
The synchronous way gives me this error:
Severity Code Description Project File Line Suppression State Error CS0266 Cannot implicitly convert type 'MongoDB.Driver.IFindFluent<BankingAppLibrary.Models.UserModel, BankingAppLibrary.Models.UserModel>' to 'BankingAppLibrary.Models.UserModel'. An explicit conversion exists (are you missing a cast?) BankingAppLibrary C:\Users\lucas\source\repos\BankingApp\BankingAppLibrary\DataAccess\MongoUserData.cs 36 Active
CodePudding user response:
You need to add .FirstOrDefaultAsync()
at the end of IFindFluent<UserModel, UserModel>
in order to return the value with Task<UserModel>
.
And since your method is an asynchronous method, don't forget to add await
as well.
Your code should be as below:
public async Task<UserModel> GetLastCreatedUser()
{
return await _users
.Find(_ => true)
.SortByDescending(u => u.DateCreated)
.Limit(1)
.FirstOrDefaultAsync();
}