Can't get c# linq query to compile with joins

2019-06-15 05:59发布

问题:

Below is a cut down example of some c# code I can't get to compile while doing some linq joins. Does anyone know why this doesn't compile?

The error is

Type arguments cannot be inferred from the query

(In my real code Fetch() returns an 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);
        }
    }
}

回答1:

This join is the wrong way round:

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

It should be:

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

The range variable you introduce always has to be on the right hand side of the equals. Normally the compiler is pretty good about telling you that in the error message, mind you...