Craig
Craig

Reputation: 18734

Left join in Linq to Entities

I am trying to do a left join using Linq, and failing. I have tried to follow a few examples, and ended up with this (failinmg) linq query:

   var defaultCategories = (from cats in Db.categories
                                 join defaults in Db.payee_default_category on cats.category_id equals
                                     defaults.category_id
                                     into merged
                                 from results in merged.DefaultIfEmpty()
                                 select new {cats.category_id, cats.description}).ToList();

So, I need to get ALL items in my Categories table, join to a payee_default_category on Categories.category_id = Payee_Default_Category.Category_id, and return the Category_id, the Category.Description, and a boolean of if there is a record in the payee_default_category table.

However, (overlooking the fact that I am not showing if there is a matching record...) at runtime, I get an error:

"LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable1[Data.payee_default_category] DefaultIfEmpty[payee_default_category](System.Collections.Generic.IEnumerable1[Data.payee_default_category])' method, and this method cannot be translated into a store expression."

Upvotes: 1

Views: 910

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156748

First of all, the DefaultIfEmpty method is not supported in version 1 of Entity Framework, but it is supported in version 4. You may want to upgrade.

Secondly, since you're only looking for a boolean to determine whether there are any defaults, you aren't doing a real outer join so much as an "exists," and you should be able to achieve it like this:

var defaultCategories = 
   (from cats in Db.categories
    let defaults = Db.payee_default_category.Where(
        d => d.category_id == cats.category_id)
    select new {cats.category_id, cats.description, hasDefaults = defaults.Any()})
    .ToList();

Also, your Entity Framework context would ideally be set up with table mappings, which would make your query even simpler:

var defaultCategories = 
    (from c in Db.categories
     select new {c.category_id, c.description, 
         hasDefaults = c.payee_default_categories.Any()})
    .ToList();

Upvotes: 2

Related Questions