4

I am trying to join two tables together using C# linq to entities.

One table has clients, the other table has licences. The tables are joined by Client_ID and ClientLicence_ClientID. For some reason (they are not my tables) the Client_ID is an int, and the ClientLicence_ClientID is a string.

The code I have is:

var licences = (from client in entities.Clients
                            join licence in entities.ClientLicences
                            on new { clientId = SqlFunctions.StringConvert((double)client.Client_ID) } equals
                            new { licence.ClientLicence_ClientID }
                            into clientGroup
                            where (filter.clientId == 0 || client.Client_ID == filter.clientId)
                            select licence);

When I try to compile this I get an error: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.

If I comment out the where statement then it works (albeit without filtering results).

The filter variable is a class that is passed in to the function. It only has one propery: int clientId.

Nigel Ellis
  • 601
  • 1
  • 8
  • 18
  • What you said about commenting out the 'where' clause - I checked specifically this case and no, it does not work, it doesn't even compile. It's the same error that you get here. Unless you changed more than just commenting out the `where` part – Joanna Derks May 19 '12 at 20:59

1 Answers1

6

Look at your join:

join licence in entities.ClientLicences on
new { clientId = SqlFunctions.StringConvert((double)client.Client_ID) }
equals
new { licence.ClientLicence_ClientID }
into clientGroup

The key types are:

  • An anonymous type with a property called clientId
  • An anonymous type with a property called ClientLicence_ClientID

Those two anonymous types can't be compared for equality. I suspect you don't need anonymous types at all here, actually. I'd expect this to work:

join licence in entities.ClientLicences on
SqlFunctions.StringConvert((double)client.Client_ID)
equals
licence.ClientLicence_ClientID
into clientGroup

(Obviously you don't need all the new lines - I was just trying to separate out the various bits for clarity.)

You claim that without the where clause it works - but that would be very surprising, given that it's the join that's a problem.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194