我需要將查詢作為字串而不是 lambda 運算式執行,因為我很難使用模擬框架來為我的專案創建單元測驗。
換句話說,我想修改我的IDatabase界面:
Interface IDatabase
{
IEnumerable<User> Find(Expression<Func<User, bool>> filter);
}
到:
Interface IDatabase
{
IEnumerable<User> Find(string query);
}
我已經有很多用運算式撰寫的查詢。因此,我創建了這段代碼來將運算式轉換為 JSON 物件:
using MongoDB.Driver;
using System.Linq.Expressions;
class Program
{
// Example of a collection I store on my DB
class User
{
public string _id { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
}
// Main method
public static void Main()
{
var json = ExpressionToJson<User>(x => x.Name.Contains("Tono") && x.DateCreated < DateTime.UtcNow);
// outputs:
// { "Name" : /Tono/s, "DateCreated" : { "$lt" : ISODate("2022-01-21T01:21:27.975Z") } }
Console.WriteLine(json);
}
/// <summary>
/// Method that will convert an expression to a string
/// </summary>
public static string ExpressionToJson<T>(Expression<Func<T, bool>> filter)
{
MongoClient MongoClient = new MongoClient();
var db1 = MongoClient.GetDatabase("DoesNotMatter");
var collection = db1.GetCollection<T>("DoesNotMatter");
var query = collection.Find(filter);
var json = query.ToString();
if (string.IsNullOrEmpty(json))
return "{}";
// json should look something like this
// find({ "Name" : /Tono/s, "DateCreated" : { "$lt" : ISODate("2022-01-21T01:11:47.772Z") } })
// remove the find( at the beginning and last parenthesis
if (json.StartsWith("find("))
return json.Substring(5, json.Length - 6);
throw new NotImplementedException("Did serializer changed?");
}
}
如您所見,此代碼可以轉換運算式
x => x.Name.Contains("Tono") && x.DateCreated < DateTime.UtcNow
轉 JSON
{ "Name" : /Tono/s, "DateCreated" : { "$lt" : ISODate("2022-01-21T01:24:38.628Z") } }
如何簡化ExpressionToJson方法?如果我可以避免創建一個實體,MongoClient然后創建一個資料庫實體,然后再創建一個實體IMongoCollection<TDocument>來序列化我需要的運算式,那將是很酷的。
uj5u.com熱心網友回復:
也許,您可以撰寫一個IMongoCollection擴展方法并采用IFindFluent<T, T>.Filter.Render(類似于
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418494.html
標籤:
