Cameron Castillo
Cameron Castillo

Reputation: 2832

LINQ to SQL .Join syntax

I'm struggling with the .Join method chaining syntax of LINQ.
I need to use this syntax so my query return IQuerable results, instead of IEnumerable.

I want to join Users with UserGroups, and return a new object that includes fields from both tables. What is the correct syntax for the JOIN operation here?

var q = dc.Users
    .Join(dc.UserGroups, 
          p => p.UserGroupID, 
          s => s.UserGroupID, 
          x => x.UserGroup) //what is the right syntax?
    .Where(p => p.User.DepartmentID == '123')
    .OrderBy(p => p.User.UserName)
    .Select(p => new UserStruct 
        { 
            UserID = p.UserID,  
            UserName = p.User.UserName,  
            FullName = p.User.FullName,  
            UserGroup = p.UserGroup  
        });

Error here is :

The type arguments for method ....cannot be inferred from the usage.

Upvotes: 2

Views: 114

Answers (1)

Håkan Fahlstedt
Håkan Fahlstedt

Reputation: 2095

Something like this:

var q = dc.Users
    .Join(dc.UserGroups, 
          p => p.UserGroupID, 
          s => s.UserGroupID, 
          (u, g) => new { User = u, UserGroup = g}) 
    .Where(p => p.User.DepartmentID == '123')
    .OrderBy(p => p.User.UserName)
    .Select(p => new UserStruct 
        { 
            UserID = p.User.UserID,  
            UserName = p.User.UserName,  
            FullName = p.User.FullName,  
            UserGroup = p.UserGroup  
        });

Upvotes: 2

Related Questions