Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to LINQ C# [Joining multiple table]

I am working on this query in my sql server

select a.care_type_id, a.description,
isChecked = case when b.care_type_id is null then 'false' else 'true' end
from caretype a
left join patientinsurancetacitem b on a.care_type_id = b.care_type_id and
b.tac_id = 1

I want to translate the query into LINQ. However, I am having trouble with the and operator. I have this code so far;

from a in context.CareTypes
join b in context.PatientInsuranceTACItems on a.care_type_id equals
b.care_type_id into x
from xx in x.Where(w => w.tac_id == 1).DefaultIfEmpty()
                   select new { 
                   isChecked = (b.care_type_id == null ? false : true),
                   care_type_id = a.care_type_id,
                   description = a.description}

And, also, I cannot get the b that I equated in isChecked variable. From where will I start modifying in order to get the same result as my sql query? In where I got it wrong?

like image 238
Mr.Right Avatar asked Mar 12 '23 17:03

Mr.Right


2 Answers

Try this

from a in context.caretype
join b on context.patientinsurancetacitem
      on new { CA = a.care_type_id, CB =  1}  equals
         new { CA = b.care_type_id, CB =  b.tac_id}
      into tmp from b in tmp.DefaultIfEmpty()
select new
{
    care_type_id = a.care_type_id, 
    description = a.description,
    checked = (b != null) // Or ((b == null) ? false : true)
}

Also check this StackOverflow answer.

like image 115
NEER Avatar answered Mar 19 '23 07:03

NEER


The very simple example about joining on multiple columns is ;

from x in entity1
             join y in entity2
             on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }
like image 35
ilkerkaran Avatar answered Mar 19 '23 06:03

ilkerkaran