Click here to Skip to main content
14,362,554 members
Rate this:
Please Sign up or sign in to vote.
See more:
I want to convert following SQL query into LINQ lambda expression.


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.
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 5:45am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

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:

SELECT * 
FROM   tbLease_Approval 
WHERE  (UserRole = 'HOD'     AND IsApproved = 1)
OR     (UserRole = 'Finance' AND IsApproved = 0)
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

A quick rewrite of your SQL query might make things easier:
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:
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;
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100