Don't use Linq with nested List <> class in MongoDb C #

I have the following classes:

public class Company
{
   [BsonId]
   public string dealerId = null;

   public List<Dealer> dealers = new List<Dealer>();
}

public class Dealer
{        
   public string dId = null;          
   public int dIndex = -1;

   public List<AutoStore> stores = new List<AutoStore>();
}

public class AutoStore
{
   public string type = null; 
   public  Dictionary<string, object> data = new Dictionary<string, object>();
}

      

I can store class objects Company

in Mongo with Insert()

. The problem is I am looking for a document and trying to use LINQ on elements List<>

. I get an exception all the time.

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

      

Running this code I get:

System.NotSupportedException: Unable to determine serialization information for expression: Enumerable.Count

I just started using Mongo today, but I thought the support was LINQ

more mature. Can anyone tell me if I can query the nested array like I did with C#

and LINQ

?

As soon as I delete Where()

in any of List<>

, this exception is not thrown

+3


source share


2 answers


Based on your exclusion, the problem area is inside where you follow the instructions Where

.

As I said in my comment. Try to do:

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

      



You are currently doing something like:

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

      

Then you check to see if there are any

dealers with shops, triggering a count and checking if it's greater than 0 to get bool

at that location. All of this is the same as a challenge IEnumerable.Any()

. See if this works? :)

+4


source


You can write your query more efficiently as

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

      

If the Mongo querty provider is trying to maintain IList

, you can find



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

      

works better. If so, reports of the maturity of the MongoDBs query provider are exaggerated.

+3


source







All Articles