'Using C# LINQ with MongoDB Find
I am only about 3 days into using MongoDb and C# driver so be gentle. ;-)
I have a MongoDB query working with AsQueryable.
I would like to use the collection.FindAsync(Func) instead of the AsQueryable, but still passing in my own lambda express. This is because I want to abstract all the MongoDb into a library so that my app code doesn't know what DB I am using.
I am also not crazy about having a lot of methods for each collection. Also, AsQueryable isn't easy for async.
Suggestions?
Calling method
bool CheckIfClassNumberExist()
{
var retCheck = _dbAccess.Find<ShowClass>(
c => c.ClassNum == Model.ClassNum);
return retCheck.IsSuccess();
}
// Find method in DbAccess.cs
public Result<T> Find<T>(Func<T, bool> func)
{
try
{
return TryFind();
}
catch (Exception e)
{
_logger.Error(e);
return Result.Failure<T>().WithMessage("Not found!");
}
Result<T> TryFind()
{
var table = typeof(T).Name;
CheckDb();
var collection = _db!.GetCollection<T>(table);
var query = collection.AsQueryable().Where(func).FirstOrDefault();
//var query = await collection.FindAsync(func);
if (query is not null)
return Result.Success<T>(query);
return Result.Failure<T>().WithMessage("Not found!");
}
This doesn't compile: MongoDbAccess.cs Shared.MongoDBLibrary Argument 1: cannot convert from 'System.Func<T, bool>' to 'MongoDB.Driver.FilterDefinition'
async Task<Result<T>> TryFind2()
{
var table = typeof(T).Name;
CheckDb();
var collection = _db!.GetCollection<T>(table);
//var query = collection.AsQueryable().Where(func).FirstOrDefault();
var query = await collection.FindAsync<T>(func);
if (query is not null)
return Result.Success<T>(query);
return Result.Failure<T>().WithMessage("Not found!");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
