Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't this Linq compile?

In this simplified version of my actual problem, I have two tables: User and Metadata. Each user can have a varied number of metadata entries associated with them via a FKEY.

This Linq compiles fine:

var user = from u in Context.Users
           join m in Context.Metadata
           on u.id equals m.userid
           select new { u.id, m.value }

However, if I replace the 'on' clause line to be:

on new { u.id } equals new { m.userid }

it fails to compile with this error:

error CS1941: The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'Join'.

Does anyone know why?

And for bonus points:

I'm ultimately trying to accomplish a query like this:

var user = from u in Context.Users
           join m in Context.Metadata
           on new { u.id, "mystring" } equals new { m.userid, m.key }
           select new { u.id, m.value }

Note the use of the literal "mystring". Needless to say, that doesn't work either.

Thanks!

EDIT: SLaks's answer worked, but just to be fully clear about what he's talking about, the final on clause that works looks like:

on new { id = u.id, key = "foo" } equals new { id = mu.userid, key = m.key }
like image 850
jwd Avatar asked Jan 19 '23 17:01

jwd


1 Answers

The property names in your anonymous types must match.

You can specify the names like this: new { UserId = u.id, Key = "mystring" }

like image 189
SLaks Avatar answered Jan 29 '23 00:01

SLaks