Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c# - Translate Queryable<T> back to IMongoQuery

Consider the following code

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

The actual query is very complex and I don't like building it using QueryBuilder instead of LINQ.

So I want to convert it back to IMongoQuery to use in myCollection.Group() call since there is no GroupBy support through LINQ.

Is it possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edited answer:

I realized that there already is an official way to get the Mongo query from a LINQ query (I should have known!). You have to downcast the IQueryable<T> to a MongoQueryable<T> to get access to the GetMongoQuery method:

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

Original answer:

At the moment there is no officially supported way to do that, but in the near future we do intend to make it easy to find out what MongoDB query the LINQ query was mapped to.

In the short term you could use the following undocumented internal methods to find out what MongoDB query the LINQ query is mapped to:

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

But at some point you might need to switch from these undocumented methods to officially supported methods (the undocumented methods might change or be renamed in the future).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...