考慮下面的代碼翻譯可查詢<T>回IMongoQuery
var q = from e in myCollection.AsQueryable<Entity>() where e.Name == "test" select e;
的實際查詢是非常複雜的,我不喜歡使用QueryBuilder的,而不是LINQ構建它。
所以我想將它轉換回IMongoQuery以在myCollection.Group()調用中使用,因爲沒有通過LINQ支持GroupBy。
可能嗎?
考慮下面的代碼翻譯可查詢<T>回IMongoQuery
var q = from e in myCollection.AsQueryable<Entity>() where e.Name == "test" select e;
的實際查詢是非常複雜的,我不喜歡使用QueryBuilder的,而不是LINQ構建它。
所以我想將它轉換回IMongoQuery以在myCollection.Group()調用中使用,因爲沒有通過LINQ支持GroupBy。
可能嗎?
編輯答案:
我意識到,已經有一個正式的方式從LINQ查詢得到蒙戈查詢(我應該知道!)。你必須垂頭喪氣的IQueryable的< T>的MongoQueryable < T>獲得訪問GetMongoQuery方法:
var linqQuery = from e in collection.AsQueryable<Entity>() where e.Name == "test" select e;
var mongoQuery = ((MongoQueryable<Entity>)linqQuery).GetMongoQuery();
原來的答覆:
目前有沒有官方支持的方式來做到這一點,但在不久的將來,我們打算輕鬆找出MongoDB查詢LINQ查詢所映射到的內容。
你可以使用下面的無證內部的方法來找出MongoDB的查詢LINQ查詢短期內被映射到:
var linqQuery = from e in collection.AsQueryable<Entity>() where e.Name == "test" select e;
var translatedQuery = (SelectQuery)MongoQueryTranslator.Translate(linqQuery);
var mongoQuery = translatedQuery.BuildQuery();
但在某些時候,你可能需要從這些無證的方法來切換官方支持的方法(未記錄的方法可能會改變或將來重新命名)。
根據羅伯特·斯塔姆的回答一個簡單的擴展:
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);
這個傷心地扔掉原LINQ語句的所有排序依據電話。您必須將它們應用回Mongo風格。 – Nashenas 2015-10-08 14:32:05