Monday, August 17, 2009

Creating “In” or “Exists” clauses in EntityFramework

To create the equivalent of a SQL “Exists” clause in EntityFramework, do the following:

ddlRecipe.DataSource = from r in _global.db.Recipe
              where (from    u in _global.db.RecipeUser
                     where u.UserId == _global.CurrentUser.Id
                        && u.RecipeId == r.ID
                     select u.RecipeId).Any()
                || (r.HTIRecipe && _global.CurrentUser.HTIEmployee)
                orderby r.Name
              select new { r.ID, r.Name };

In this case the query is returning all Recipes where there exists a RecipeUser in the other collection.

No comments:

Post a Comment