Click here to Skip to main content
15,884,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to convert following SQL query into LINQ lambda expression.


SQL
SELECT     Hod.* 
FROM       (
               SELECT * 
               FROM   tbLease_Approval 
               WHERE  UserRole = 'HOD' 
               AND    IsApproved = 1)
           ) AS Pm 
INNER JOIN (
               SELECT * 
               FROM   tbLease_Approval 
               WHERE  UserRole = 'Finance' 
               AND    IsApproved = 0
           ) AS Hod 
ON         Pm.LeaseNo = Hod.LeaseNo


What I have tried:

I tried to made query for inner join. But unable to create subquery part using LINQ lambda expression in following query.
C#
var test = db.Ett_LeaseApprovalDetails.Join(db.Ett_LeaseApprovalDetails,
                            r1 => r1.LeaseNo, r2 => r2.LeaseNo, (r1, r2) => 
                            new { r2.LeaseNo, r2.IsApproved, r2.IsRejected, r2.Remarks });
Posted
Updated 23-Sep-19 4:45am
v2

This may not help you, but our team puts complex queries into a stored proc, and if necessary, uses Linq to filter out what we don't want in the app. That leaves the queries (that sql server is optimized to perform well) in the database, and is realizes significantly reduced Linq complexity and performance hit in the C# code. It also lets us deploy just database changes if the complex query needs to be adjusted.

Finally, your query seems overly complex. Wouldn't this do the job as well:

SQL
SELECT * 
FROM   tbLease_Approval 
WHERE  (UserRole = 'HOD'     AND IsApproved = 1)
OR     (UserRole = 'Finance' AND IsApproved = 0)
 
Share this answer
 
v2
A quick rewrite of your SQL query might make things easier:
SQL
SELECT
    *
FROM
    tbLease_Approval As Hod
WHERE
    Hod.UserRole = 'Finance'
And
    Hod.IsApproved = 0
And
    Exists
    (
        SELECT 1
        FROM tbLease_Approval As Pm
        WHERE Pm.UserRole = 'HOD'
        And Pm.IsApproved = 1
        And Pm.LeaseNo = Hod.LeaseNo
    )
;
That should translate nicely to LINQ:
C#
var test = from hod in db.Ett_LeaseApprovalDetails
           where hod.UserRole = "Finance"
           && !hod.IsApproved
           && db.Ett_LeaseApprovalDetails.Any(pm => pm.UserRole = "HOD" && pm.IsApproved && pm.LeaseNo == hod.LeaseNo)
           select hod;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900