Pages

Tuesday 19 August 2014

Left Outer Join in Linq

Left Outer Join in Linq to Entites:

So guys here I am going to explain you the Left Outer Join in Linq to entities. Here I performed left outer join on the results of two separate join queries. If left table does not contains value then DefaultIfEmpty() is used to select default value for that record.

Linq Query : var result=(from s in db.schedules join sp in db.programs on s.scheduleId equals sp.scheduleId join sub in ( from pc in db.PersonCategories join fc in db.FilmCrews on pc.PersonCategoryCode equals fc.PersonCategoryCode where (pc.PersonCategoryId == "PC0000001") select new { fc.Name, fc.programmeId } ) on sp.programmeId equals sub.programmeId into eGroup from sub in eGroup.DefaultIfEmpty() where (s.date >= "1 aug 2014") orderby s.date, sp.starttime select new { s.date, sp.starttime, s.programme_name, sub.Name }); Code Explanation :

In above code I performed join operation on schedule and programs table on the basis of scheduleId which is primary key in schedule table and forign key in programs table. Similarly I performed the join on PersonCategories and FilmCrews tables, on the basis of PersonCategoryCode which is primary key in first table and foreign key in second table. Now on the result of these two queries I performed left outer join as there is only join keyword which is used to perform all types of join operations. In above code I performed left outer join on the field programmeId which is present in the both the query results. To perform left outer join I used one Linq method named DefaultIfEmpty(). As you know in left outer join all values from left table are selected and only available values from second table are selected, so here DefaultIfEmpty() method is used for the same reason this method put Default value i.e. null in the place where there is no value for the current record.

Subquery in Linq :

In above code I also performed the subquery operation, i.e. here I performed left outer join on the subquery result. Here I created one alias named sub which holds the result of subquery. Then I performed Left outer join on the result of first join operation and on the result of subquery.

No comments:

Post a Comment