1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

by the way you can also .FirstOrDefault() instead of .Take(1)so it will return an entity - not IEnumerable<Entity>.
0
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.