MetalAdam
MetalAdam

Reputation: 576

Converting an advanced query from SQL to LINQ

Still getting used to LINQ syntax, and have come across this query that I need to create in LINQ - but not exactly sure how.

SELECT *,
   (SELECT 1 FROM Applications 
   WHERE Applications.jID = Jobs.ID 
   AND Applications.uID = @uID) AS Applied 
FROM [Jobs]

Playing in LinqPad, but the interface isn't really helping (at least with what I can see).

Upvotes: 0

Views: 183

Answers (3)

Daniel
Daniel

Reputation: 11064

I recommend checking out the tool Linqer -- which converts SQL to Linq code. It's not free but there is a 10 day trial.

enter image description here

Upvotes: 0

Christopher Rayl
Christopher Rayl

Reputation: 329

var jobs = from j in this.db.Jobs
           where !j.Applications.Any(x => x.UserId == currentUserId)
           select j;

Upvotes: 0

Chris McAtackney
Chris McAtackney

Reputation: 5232

Based on the link provided by Paul Sasik, and his advice that you're after a LEFT OUTER JOIN, this query should meet your requirements;

var query = from job in jobs
            join app in applications on job.ID equals app.jID into grouped
            from subApp in grouped.DefaultIfEmpty()
            select new { Job = job, Applied = (subApp != null) };

EDIT: To filter by user, update the query as follows;

var query = from job in jobs
    join app in
    (
        from userApp in applications where userApp.uID == uID select userApp
    ) on job.ID equals app.jID into grouped
    from subApp in grouped.DefaultIfEmpty()
    select new { Job = job, Applied = (subApp != null) };

I personally would have reverted to just using the .Where() method directly at this point, but just thought I'd keep everything consistent and continue using the query syntax.

Upvotes: 2

Related Questions