How to write LINQ query for Inner Join with and condition?

Sometimes, you need to apply inner join with and condition. To write query for inner join with and condition you need to make two anonymous types (one for left table and one for right table) by using new keyword and compare both the anonymous types as shown below:

DataContext context = new DataContext();
var q = from cust in context.tblCustomer join ord in context.tblOrder
// Both anonymous types should have exact same number of properties having same name and datatype
on new {
	a = (int ? ) cust.CustID, cust.ContactNo
}
equals new {
	a = ord.CustomerID, ord.ContactNo
}
select new {
	cust.Name, cust.Address, ord.OrderID, ord.Quantity
};

// Generated SQL

SELECT
[t0].[Name],
[t0].[Address],
[t1].[OrderID],
[t1].[Quantity]
FROM
[tblCustomer] AS [t0]
INNER JOIN [tblOrder] AS [t1] ON (
([t0].[CustID]) = [t1].[CustomerID]
)
AND (
[t0].[ContactNo] = [t1].[ContactNo]
)

Note –

  1. Always remember, both the anonymous types should have exact same number of properties with same name and Datatype otherwise you will get the compile time error “Type inference failed in the call to Join”.
  2. Both the comparing fields should define either NULL or NOT NULL values.
  3. If one of them is defined NULL and other is defined NOT NULL then we need to do typecasting of NOT NULL field to NULL data type like as above fig.
Tagged , . Bookmark the permalink.

Leave a Reply