【问题标题】:Can't get c# linq query to compile with joins无法使用连接编译 c# linq 查询
【发布时间】:2012-04-14 06:26:56
【问题描述】:

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

错误是

无法从查询中推断出类型参数

(在我的真实代码中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);
        }
    }
}

【问题讨论】:

    标签: c# linq join compiler-errors


    【解决方案1】:

    这个连接是错误的:

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

    应该是:

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

    您引入的范围变量必须始终位于equals右侧。通常编译器会很好地告诉你在错误消息中,请注意...

    【讨论】:

    • 非常感谢您的快速回答。你不会相信我在这上面浪费了多少时间。如果编译器更有帮助会更好,但您关于“您引入的范围变量始终必须在等号的右侧”的提示是我现在将致力于记忆的提示。
    猜你喜欢
    • 2011-11-14
    • 1970-01-01
    • 2021-06-23
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多