将Queryable <t>转换回IMongoQuery </t>

时间:2012-04-21 17:03:56

标签: c# linq mongodb

考虑以下代码

var q = from e in myCollection.AsQueryable<Entity>() where e.Name == "test" select e;

实际查询非常复杂,我不喜欢使用QueryBuilder而不是LINQ构建它。

所以我想将它转换回IMongoQuery以在myCollection.Group()调用中使用,因为LINQ没有GroupBy支持。

有可能吗?

2 个答案:

答案 0 :(得分:18)

编辑回答:

我意识到已经有一种官方的方式从LINQ查询中获取Mongo查询(我应该知道!)。你必须向下转换IQueryable&lt; T&gt;到MongoQueryable&lt; T&gt;访问GetMongoQuery方法:

var linqQuery = from e in collection.AsQueryable<Entity>() where e.Name == "test" select e;
var mongoQuery = ((MongoQueryable<Entity>)linqQuery).GetMongoQuery();

原始答案:

目前还没有官方支持的方法,但在不久的将来,我们打算让我们很容易找到LINQ查询被映射到的MongoDB查询。

<击>

在短期内,您可以使用以下未记录的内部方法来查找LINQ查询映射到的MongoDB查询:

var linqQuery = from e in collection.AsQueryable<Entity>() where e.Name == "test" select e;
var translatedQuery = (SelectQuery)MongoQueryTranslator.Translate(linqQuery);
var mongoQuery = translatedQuery.BuildQuery();

但在某些时候,您可能需要从这些未记录的方法切换到官方支持的方法(未记录的方法可能会在将来更改或重命名)。

答案 1 :(得分:1)

根据Robert Stam的回答进行快速扩展:

public static IMongoQuery ToMongoQuery<T>(this IQueryable<T> linqQuery)
{
    var mongoQuery = ((MongoQueryable<T>)linqQuery).GetMongoQuery();
    return mongoQuery;
}
public static WriteConcernResult Delete<T>(this MongoCollection<T> col,   IQueryable<T> linqQuery)
{
     return col.Remove(linqQuery.ToMongoQuery());
}
public static WriteConcernResult Delete<T>(this MongoCollection<T> col, Expression<System.Func<T, bool>> predicate)
{
    return col.Remove(col.AsQueryable<T>().Where(predicate).ToMongoQuery());
}

示例:

myCollection.Remove(myCollection.AsQueryable().Where(x => x.Id == id).ToMongoQuery());
myCollection.Delete(myCollection.AsQueryable().Where(x => x.Id == id));
myCollection.Delete(x => x.Id == id);