我一直在尝试使用Linq将表达式的动态列表传递给MongoDB C#驱动程序查询。。。例如,这种方法适用于针对ORM的常规Linq查询,但在应用于MongoDB查询时会导致错误。。。(仅供参考:我也在使用LinqKit的PredicateBuilder)
//
// I create a List of Expressions which I can then add individual predicates to on an
// "as-needed" basis.
var filters = new List<Expression<Func<Session, Boolean>>>();
//
// If the Region DropDownList returns a value then add an expression to match it.
// (the WebFormsService is a home built service for extracting data from the various
// WebForms Server Controls... in case you're wondering how it fits in)
if (!String.IsNullOrEmpty(WebFormsService.GetControlValueAsString(this.ddlRegion)))
{
String region = WebFormsService.GetControlValueAsString(this.ddlRegion).ToLower();
filters.Add(e => e.Region.ToLower() == region);
}
//
// If the StartDate has been specified then add an expression to match it.
if (this.StartDate.HasValue)
{
Int64 startTicks = this.StartDate.Value.Ticks;
filters.Add(e => e.StartTimestampTicks >= startTicks);
}
//
// If the EndDate has been specified then add an expression to match it.
if (this.EndDate.HasValue)
{
Int64 endTicks = this.EndDate.Value.Ticks;
filters.Add(e => e.StartTimestampTicks <= endTicks);
}
//
// Pass the Expression list to the method that executes the query
var data = SessionMsgsDbSvc.GetSessionMsgs(filters);
GetSessionMsgs()方法是在数据服务类中定义的。。。
public class SessionMsgsDbSvc
{
public static List<LocationOwnerSessions> GetSessionMsgs(List<Expression<Func<Session, Boolean>>> values)
{
//
// Using the LinqKit PredicateBuilder I simply add the provided expressions
// into a single "AND" expression ...
var predicate = PredicateBuilder.True<Session>();
foreach (var value in values)
{
predicate = predicate.And(value);
}
//
// ... and apply it as I would to any Linq query, in the Where clause.
// Additionally, using the Select clause I project the results into a
// pre-defined data transfer object (DTO) and only the DISTINCT DTOs are returned
var query = ApplCoreMsgDbCtx.Sessions.AsQueryable()
.Where(predicate)
.Select(e => new LocationOwnerSessions
{
AssetNumber = e.AssetNumber,
Owner = e.LocationOwner,
Region = e.Region
})
.Distinct();
var data = query.ToList();
return data;
}
}
使用LinqKit PredicateBuilder,我只需将提供的表达式添加到一个"AND"表达式中。。。并将其应用于Where()子句中的任何Linq查询。此外,使用Select()子句,我将结果投影到预定义的数据传输对象(DTO)中,并且只返回DISTINCT DTO。
当我反对我的Telerik ORM上下文实体集合时,这种技术通常有效。。。但是当我在Mongo文档集合中运行这个时,我会得到以下错误。。。
不支持的筛选器:Invoke(e=>(e.Region.ToLower()=="center"),{document})
当然有一些我不清楚的事情在背后发生。在MongoDB的C#驱动程序文档中,我发现了以下注释。。。
"当投影标量时,驱动程序会将标量包装成文档,因为MongoDB要求聚合管道的输出是文档"
但老实说,我不确定这必然意味着什么,也不确定这是否与这个问题有关。错误中出现的"{document}"表明它可能是相关的。
任何额外的想法或见解都将不胜感激。已经坚持了两天了。。。
我确实找到了这篇文章,但到目前为止,我不确定接受的解决方案与我所做的有多大不同。
4年后我将再次讨论这个问题,因为虽然我最初的假设确实有效,但它的工作方式是错误的,即从Mongo中提取所有记录,然后在内存中过滤它们,更糟糕的是,它对数据库进行同步调用,这总是一个坏主意。
LinqKit的扩展扩展方法的神奇之处
这将调用表达式树扁平化为Mongo驱动程序可以理解并执行的内容。
.Where(predicate.Expand())