为什么这个 Linq 无法编译?
在我的实际问题的简化版本中,我有两个表:User
和 Metadata
。 每个用户都可以通过 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 }
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 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
匿名类型中的属性名称必须匹配。
您可以指定如下名称:
new { UserId = u.id, Key = "mystring" }
The property names in your anonymous types must match.
You can specify the names like this:
new { UserId = u.id, Key = "mystring" }