不能在MongoDb C#上使用Linq和嵌套类List

我有以下课程:

public class Company { [BsonId] public string dealerId = null; public List dealers = new List(); } public class Dealer { public string dId = null; public int dIndex = -1; public List stores = new List(); } public class AutoStore { public string type = null; public Dictionary data = new Dictionary(); } 

我可以使用Insert()Company类对象存储在Mongo中。 问题是当我搜索文档并尝试在List项目上使用LINQ时。 我不断得到例外。

 var query = collection.AsQueryable() .Where(cpy => cpy.dealers.Where(dlr => dlr.stores.Count == 1).Count() > 0) ; 

运行此代码我得到:

System.NotSupportedException:无法确定表达式的序列化信息:Enumerable.Count

我今天刚开始使用Mongo,但我认为LINQ支持更加成熟。 任何人都可以告诉我,我是否可以像C#LINQ那样进行嵌套数组查询?

只要删除任何List上的Where() ,就不会抛出该exception

在你的例外情况下,问题区域就在你在Where做声明。

正如我在评论中所说。 试着做:

 var v = collection.AsQueryable().Where(cpy => cpy.Dealers.Any(dlr => dlr.Stores.Count == 1)); 

您目前正在做类似的事情:

 var dealers = collection.AsQueryable().Select(cpy => cpy.Dealers); var dealersWithStores = dealers.Where(dealer => dealer.Stores.Count == 1); 

然后,您通过调用计数检查是否有any经销商,并检查是否超过0以使您的bool在哪里。 所有这些都与调用IEnumerable.Any()相同。 看看这是否有效? 🙂

你可以更有效地写信给你

 var query = collection.AsQueryable() .Where(c => c.dealers.Any(d => d.stores.Count == 1); 

如果Mongo querty提供商正在努力支持IList ,您可能会发现

 var query = collection.AsQueryable() .Where(c => c.dealers.Any(d => d.stores.Count() == 1); 

效果更好。 如果是这样,MongoDBs查询提供程序成熟度的报告被夸大了。