Search code examples
c#linqlinq-to-sql

How to write LINQ in C# with joins based on SQL Query?


I need to write a linq based on the following query.

IN SQL Server,

select EXID,ID,NAME 
from Table1 A
join Table2 B on A.BXID = B.BID
left outer join Table3 C ON C.AXID = A.ID
AND C.EXID = (some number/NULL)

This gives me 300 records

In LINQ,

try
        {
            using (var context = new cltransformationContext())
            {
                var Details = (
                            from A in context.Table1
                            join B in context.Table2 on A.BXID equals B.BID
                            join C in context.Table3 on A.ID equals C.AXID  
                select new Table1()
                           {
                            ID = A.ID,
                            name = A.NAME + '-' B.Name
                            }).ToList();
                return Details;
            }
        }

I am getting 5000 records here.

I have missed left outer join and C.EXID = (some number/NULL) condition. How to do that in the query?

I should only get the 300 records.


Solution

  • This query will create LEFT JOIN:

    var query =
        from A in context.Table1
        join B in context.Table2 on A.BXID equals B.BID
        from C in context.Table3.Where(C => A.ID == C.AXID && C.EXID == ...).DefaultIfEmpty()
        select new Table1
        {
            ID = A.ID,
            name = A.NAME + '-' B.Name
        };