Mr.Right
Mr.Right

Reputation: 49

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?

Upvotes: 4

Views: 187

Answers (2)

neer
neer

Reputation: 4082

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.

Upvotes: 5

ilkerkaran
ilkerkaran

Reputation: 4344

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 }

Upvotes: 2

Related Questions