Posted By

housecor on 12/23/10


Tagged


Versions (?)

LINQ Left join


 / Published in: C#
 

URL: http://amirrajan.net/blog/left-join-on-multiple-tables-in-linq-to-sql/

  1. from expense in expenseDataContext.ExpenseDtos
  2. where expense.Id == expenseId //some expense id that was passed in
  3. from category
  4. // left join on categories table if exists
  5. in expenseDataContext.CategoryDtos
  6. .Where(c => c.Id == expense.CategoryId)
  7. .DefaultIfEmpty()
  8. // left join on expense type table if exists
  9. from expenseType
  10. in expenseDataContext.ExpenseTypeDtos
  11. .Where(e => e.Id == expense.ExpenseTypeId)
  12. .DefaultIfEmpty()
  13. // left join on currency table if exists
  14. from currency
  15. in expenseDataContext.CurrencyDtos
  16. .Where(c => c.CurrencyID == expense.FKCurrencyID)
  17. .DefaultIfEmpty()
  18. select new
  19. {
  20. Expense = expense,
  21. // category will be null if join doesn't exist
  22. Category = category,
  23. // expensetype will be null if join doesn't exist
  24. ExpenseType = expenseType,
  25. // currency will be null if join doesn't exist
  26. Currency = currency
  27. }

Report this snippet  

You need to login to post a comment.