无法使用连接编译 C# linq 查询

2024-02-13

下面是一些我在执行一些 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);
        }
    }
}

这种连接方式是错误的:

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

它应该是:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法使用连接编译 C# linq 查询 的相关文章

随机推荐