Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
        }
    }
}
like image 321
chrisp_68 Avatar asked Mar 30 '12 14:03

chrisp_68


1 Answers

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...

like image 50
Jon Skeet Avatar answered Nov 16 '22 00:11

Jon Skeet