LINQ - Left join with where conditions

Left joins don't come natural to LINQ but the solution is not that complicated.

Below is my example

I needed to pass in 3 fields for my where clause and I was getting back the LoginName field from the USERS table - unfortunately sometimes this field was empty and my join would not work - in the SQL we know and love this is easily accomplished with a left join (take all the fields from the first table or the table on the left and any that match in the second table)

Below you can see how this works. The 'subgroup' referenced below is just an alias, there is no table named subroup - almost acting like a temptable.

 var mygroupitems = (from e in MyEntities.Terr_History
                            join p in MyEntities.Users on e.Approver_User_Id  equals p.Users_Id into XX
                            from subgroup in XX.DefaultIfEmpty()
                            where e.tdg_PID == pid  && e.Account_Code==accountcode
                            && e.Status_=="Active"

                            select new Management.Data.DTO.Terr_HistoryDTO
                            {
                                Territory_Type=e.Territory_Type,
                                Rn_Descriptor = e.Rn_Descriptor,
                               Approver_User_Id=e.Approver_User_Id,
                              Approver_UserName = (subgroup==null? string.Empty:subgroup.Login_Name),
.... and so on

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax