使用LinqtoEntities lambda C#选择项目

时间:2012-12-24 14:19:24

标签: c# .net linq entity-framework lambda

我在Visual Studio 2012中使用Entity Framework代码优先技术 这是我的背景

public class BakingWebContext : DbContext
{
        public DbSet<Recipe> Recipes { get; set; }
        public DbSet<Category> Categories { get; set; }
}

我有一个分类类

public class Category
{
        [Key]
        public int CategoryId { get; set; }
        [Required]
        public string Name { get; set; }
        public string Description { get; set; }
        public string ImageUrl { get; set; }

        public virtual ICollection<Recipe> Recipes { get; set; }

}

它包含一个虚拟的食谱集合

public class Recipe
{
        [Key]
        public int RecipeId { get; set; }
        [Required]
        public string Title { get; set; }
        public string Description { get; set; }
        public bool IsCompanyRecipe { get; set; }
}

我正在尝试返回所有类别,包括仅使用C#

中的Lambda表达式将 IsCompanyRecipe 标记为 true 的食谱

到目前为止,我已经有了这个

var query = categories.Where(c => c.Recipes.Count > 0).SelectMany(r => r.Recipes.Where(re => re.IsCompanyRecipe == true));

返回所有公司食谱的IEnumerable<Recipe>列表,但我想返回一个IEnumerable<Category>列表,其中包含IsCompanyRecipe == true的所有食谱?

1 个答案:

答案 0 :(得分:5)

var query = (from c in categories
         from r in c.Recipes
         where r.IsCompanyRecipe == true
         select c);