Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo Driver Linq Query throws Exception

I'm using:

  • Asp.net Core 1.1
  • MongoDB Driver 2.4.4

And I'm performing the following LINQ Query:

        var collection = _db.GetCollection<TableA>("TableAs");
        var collectionTableB = _db.GetCollection<TableB>("TableBs");
        var collectionTableC = _db.GetCollection<TableCs>("TableCs");


        var query = from c in collection.AsQueryable()
                    join i in (from f in collectionTableB.AsQueryable()
                               join p in collectionTableC.AsQueryable() 
                                    on f.PcbaId equals p.PcbaId into i
                               from x in i.DefaultIfEmpty()
                               select new { f, x })
                  on c.AssemblyId equals i.f.AssemblyId into cap
                    from i in cap.DefaultIfEmpty()
                    select new ConfigurableItemDto {

                    };

When I execute this, it throws the following exception:

Expression of type 'System.Collections.Generic.IEnumerable`1[TableB]' cannot be used for parameter of type 'System.Linq.IQueryable`1[TableB]' of method 'System.Linq.IQueryable`1[<>f__AnonymousType2`2[TableB,System.Collections.Generic.IEnumerable`1[TableC]]] GroupJoin[Assembly,Pcba,String,<>f__AnonymousType2`2](System.Linq.IQueryable`1[TableB], System.Collections.Generic.IEnumerable`1[TableC], System.Linq.Expressions.Expression`1[System.Func`2[TableB,System.String]], System.Linq.Expressions.Expression`1[System.Func`2[TableC,System.String]], System.Linq.Expressions.Expression`1[System.Func`3[TableB,System.Collections.Generic.IEnumerable`1[TableC],<>f__AnonymousType2`2[TableB,System.Collections.Generic.IEnumerable`1[TableC]]]])' Parameter name: arg0

Is there something wrong with my query? Maybe my query is not supported by the MongoDB Driver?

like image 608
S P Avatar asked Sep 20 '17 10:09

S P


1 Answers

The MongoDb driver does support GroupJoin, but it seems that it doesn't support GroupJoin with a collection of anonymous types. Fortunately, your query can be rewritten as GroupJoins between MongoCollections:

var query = from a in collection.AsQueryable()
            join b in collectionTableB.AsQueryable()
                on a.AssemblyId equals b.AssemblyId into bj
            from b in bj.DefaultIfEmpty()
            join c in collectionTableC.AsQueryable() 
                on b.PcbaId equals c.PcbaId into cj
            from c in cj.DefaultIfEmpty()
            select new ConfigurableItemDto {
                 a.SomeAProperty,
                 b.SomeBProperty,
                 c.SomeCProperty,
            };

I don't have MongoDb running, so I can't try the result of this query (which I'd normally do). Please give it a try.

like image 159
Gert Arnold Avatar answered Sep 25 '22 06:09

Gert Arnold