Efcore: Unable to join using composite keys. Type cannot be inferred.

Created on 5 Jun 2018  路  3Comments  路  Source: dotnet/efcore

I want to be able to join to queries on multiple fields (composite keys).

Joining on a single field works fine:

  var query = outer.Join(
                inner: inner,
                outerKeySelector: tr => tr.TransactionId
                innerKeySelector: cua => cua.Id
                resultSelector: (tr, cua) => new
                {
                    cua.AmountApplied,
                    tr.Amount
                }
            );

but if I try to create a composite join expression:

   var query = outer.Join(
                inner: inner,
                outerKeySelector: tr => new {tr.TransactionId, tr.UserId},
                innerKeySelector: cua =>new {cua.Id, cua.UserId},
                resultSelector: (tr, cua) => new
                {
                    cua.AmountApplied,
                    tr.Amount
                }
            );

(note that all the fields above are int values).

I get an error:

```
the type arguments for method 'Queryable.Join ````

Do I need to build a non-anonymous type and custom comparer to use composite expressions in my join?

EF Core version: 2.1.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system:
IDE: (e.g. Visual Studio 2017 15.4)

closed-question customer-reported

Most helpful comment

Instead of new {o.TransactionId, o.UserId} equals new {i.Id, i.UserId}
try new {Id = o.TransactionId, o.UserId} equals new {i.Id, i.UserId}

All 3 comments

I also tried to writing the query using Linq:

 var query2 = from o in outer
                join i in inner
                    on new {o.TransactionId, o.UserId} equals new {i.Id, i.UserId} into details
                from d in details
                select d;

which produces the error:

The type of one of the expressions in the join clause is incorrect.  The inference failed in the call to 'GroupJoin'.

The type arguments cannot be inferred from the query.

Instead of new {o.TransactionId, o.UserId} equals new {i.Id, i.UserId}
try new {Id = o.TransactionId, o.UserId} equals new {i.Id, i.UserId}

NICE! I assumed the anonymous type definitions had match.. It never occurred to me that the property names needed to match as well.

Thanks @smitpatel

Was this page helpful?
0 / 5 - 0 ratings