SQL to LINQ for SubQuery Entity Framework

时间:2014-08-03 04:28:04

标签: c# sql linq entity-framework

我想将此SQL转换为LINQ但我无法编译它。这是我转换的SQL

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 )

这是我到目前为止的尝试

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)

任何帮助都将不胜感激。

TIA

2 个答案:

答案 0 :(得分:2)

注意:此代码未经测试,但我认为您希望获得每个用户的最新凭据。

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)
                  });

您可以删除.Take(1)以获取用户的所有记录,但结果仍按降序排序。

答案 1 :(得分: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)