2012-03-30 28 views
12

下面是一些c#代码的简化示例,我不能在执行一些linq连接时进行编译。有谁知道为什么这不编译?无法获得c#linq查询与连接编译

的误差

类型参数不能从查询推断

(在我真正的代码Fetch()返回IQueryable<T>

using System.Collections.Generic; 
using System.Linq; 

namespace LinqJoin 
{ 
    public class DataRepository<T> 
    { 
     public IList<T> Fetch() 
     { 
      return new List<T>(); 
     } 
    } 

    internal class SSOUser 
    { 
     public int Id { get; set; } 
    } 

    internal class UserRole 
    { 
     public int SSOUserId { get; set; } 
     public int RoleId { get; set; } 
    } 

    internal class Role 
    { 
     public int RoleId { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var users = new DataRepository<SSOUser>().Fetch(); 
      var userroles = new DataRepository<UserRole>().Fetch(); 
      var roles = new DataRepository<Role>().Fetch(); 

      var result = from u in users 
        join ur in userroles on u.Id equals ur.SSOUserId 
        join r in roles on r.RoleId equals ur.RoleId 
        select u; 

     //var x1 = users.Join(userroles, u => u.Id, ur => ur.SSOUserId, (u, ur) => new { User = u, UserRole = ur}).Join(roles, x => x.UserRole.RoleId, r => r.RoleId, res => res.User); 
     } 
    } 
} 

回答

31

此连接错误的方式轮次:

join r in roles on r.RoleId equals ur.RoleId 

它应该是:

join r in roles on ur.RoleId equals r.RoleId 

你介绍的范围变量总是要上equals右手边。通常情况下,编译器很好地告诉你,在错误信息中,请注意你...

+0

非常感谢您的快速回答。你不会相信我浪费了多少时间。如果编译器有点帮助,那将会很不错,但是关于“你所介绍的范围变量必须始终位于等号的右边”的提示是我现在要提交的内存。 – 2012-03-30 15:05:11