Linq-To-Sql查询中的模糊调用

时间:2011-08-14 17:27:14

标签: c# linq linq-to-sql

我还是Linq-To-SQL的新手,当我尝试使用join运算符(相当于SQL内部联接)时,我遇到了问题。

获取用户的所有偏好设置:

return (from u in DataContext.UserPreference
join p in DataContext.Preference on p.Id equals u.PreferenceId
where u.UserId = userId
select p).ToList();

Visual Studio告诉我,查询中的“join”运算符是Enumerable类和Queryable类之间的“模糊调用”。

我有什么想法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:6)

您的联接表达方式错误 - 您应首先使用u,然后使用p

return (from u in DataContext.UserPreference
        join p in DataContext.Preference on u.PreferenceId equals p.Id
        where u.UserId == userId
        select p).ToList();

基本上你使用连接左侧的第一个范围变量,右侧使用第二个变量。

编译器通常会发现这种错误,这恰恰表明了什么是错误的。我不知道为什么它在这种情况下没有,但无论哪种方式都应该是修复。

答案 1 :(得分:3)

我将不同意Jon。你的查询在第3行有一个赋值运算符,而不是相等运算符,所以改为

return (from u in DataContext.UserPreference
        join p in DataContext.Preference on p.Id equals u.PreferenceId
        where u.UserId == userId
        select p).ToList();