C#C
C#2y ago
Apache

CROSS APPLY within LINQ

Is there a tool I can use to directly map SQL to LINQ? I have a query that I'm not sure how to translate. Here's the SQL:

SELECT [f].[FileName], [a].[ClientName], [f].[FilenameRegex], [f].[Usernames], [f].[RateLimit], [t0].[AssignmentId], [t0].[TimeIssued], [t0].[TimeCompleted], [t0].[Status]
FROM [AssignmentDetails] AS [f]
INNER JOIN [Assignment] as [a] ON [f].[FileName] = [a].[FileName]
CROSS APPLY (SELECT TOP 1 * FROM Assignments WHERE FileName = w.FileName ORDER BY AssignmentId DESC) t0
WHERE [a].[ClientName] = "Apache"


I can't figure out how to do CROSS APPLY within LINQ.

This was my attempt, but it creates a horrible web of SQL that traverses the entire Assignments table just to find a single record.

var assignmentSummaries = ctx.AssignmentDetails
    .Where(a => a.Assignment.ClientName == command.ClientName)
    .Select(a => new AssigmentDetailsViewModel()
    {
        FileName = a.FileName,
        ClientName = a.Assignment.ClientName,
        AssignmentDetails = new()
        {
            FilenameRegex = a.FilenameRegex,
            RateLimit = a.RateLimit,
            Usernames = a.Usernames,
          
        },
        LatestFile = a.Assignment.Files
            .OrderByDescending(f => f.AssignmentId)
            .Select(f => new AssignmentFile()
            {
                AssignmentId = f.AssignmentId,
                TimeIssued = f.TimeIssued,
                TimeCompleted = f.TimeCompleted,
                Status = f.Status,
            })
            .Take(1)
    })
    .ToList();


The only way we've found that works so far is to not add the LatestFile here, and run a client-side
foreach
loop after we get the results.
Was this page helpful?