Vincent Dagpin
Vincent Dagpin

Reputation: 3611

SQL to LINQ for SubQuery Entity Framework

i want to convert this SQL to LINQ but i cant compile it. This is my sql to convert

SELECT  u.UserID ,
        A.Username ,
        A.Password ,
        A.CreatedOn
FROM    dbo.tbl_User U
        INNER JOIN dbo.tbl_UserAuthDetail A ON A.UserID = U.UserID
                                               AND A.CreatedOn IN (
                                               SELECT TOP 1
                                                        CreatedOn
                                               FROM     dbo.tbl_UserAuthDetail U2
                                               WHERE    U2.UserID = U.UserID
                                               ORDER BY CreatedOn DESC )

and this is my attempt so far

var q = from u in context.Users
                        join au in context.UserAuthDetails on u.UserID equals au.UserID && 
                        (from au2 in context.UserAuthDetails where au2.UserID == u.UserID orderby au2.CreatedOn descending select au2.CreatedOn).ToList().Contains(au.CreatedOn)

Any help would be appreciated.

TIA

Upvotes: 1

Views: 312

Answers (2)

John Woo
John Woo

Reputation: 263683

Note: This code is untested but I think you want to get the latest credential of each user.

var query = context.Users    
            .GroupJoin(context.UserAuthDetails, 
                    u => u.UserID ,     
                    d => d.UserID,   
                  (u, d) => new 
                  { 
                    User = u, 
                    Details = d.OrderByDescending(x => x.CreatedOn).Take(1)
                  });

You can remove .Take(1) to get all the records of the user and still the result is sorted in descending order.

Upvotes: 2

AD.Net
AD.Net

Reputation: 13399

from u in context.Users
join au in context.UserAuthDetails on u.UserID equals au.UserID && 
                        context.UserAuthDetails.Where(au2 => au2.UserID == u.UserID)
                                        .OrderByDescending(au2 => au2.CreatedOn)
                                        .Select(au => au2.CreatedOn)
                                        //.Take(1) //you have this in SQL
                                        .Any(auc=>auc == au.CreatedOn)

Upvotes: 0

Related Questions