这个Linq为什么不编译?

时间:2011-05-17 00:42:40

标签: linq linq-to-entities

在我的实际问题的简化版中,我有两个表:UserMetadata。 每个用户可以通过FKEY获得与其相关联的各种元数据条目。

这个Linq编译好了:

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

但是,如果我将'on'子句行替换为:

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

无法使用此错误进行编译:

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

有谁知道为什么?

奖励积分:

我最终试图完成这样的查询:

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 }

请注意使用文字"mystring"。 不用说,这也不起作用。

谢谢!

编辑: SLaks的回答有效,但为了完全清楚他正在谈论的内容,最终的on条款有效:

on new { id = u.id, key = "foo" } equals new { id = mu.userid, key = m.key }

1 个答案:

答案 0 :(得分:9)

匿名类型中的属性名称必须匹配。

您可以指定如下名称:new { UserId = u.id, Key = "mystring" }