2011-05-17 229 views
4

在我的实际问题的简化版本中,我有两个表格:UserMetadata。 每个用户可以通过FKEY获得与它们相关的各种数量的元数据条目。为什么Linq不能编译?

这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 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 } 
+0

为什么你需要比不上匿名对象的字段自己? – zerkms 2011-05-17 00:44:20

+0

@zrkms:加入两个领域。 – SLaks 2011-05-17 00:45:25

+0

@SLaks:omg,不知道linq不能这么说:-S – zerkms 2011-05-17 00:51:00

回答

9

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

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

+1

虽然我不明白你的意思,但它起作用(:在我的问题中添加了最终的工作语法。 – jwd 2011-05-17 00:53:22