2012-12-24 106 views
3

选择项目我使用实体框架代码第一种方法在Visual Studio 2012 这里是我的上下文使用LinqtoEntities拉姆达C#

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; } 
} 

我试图返回所有的食物gories仅包括有IsCompanyRecipe使用Lambda表达式在C#

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

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

返回所有的公司食谱,但我的IEnumerable<Recipe>列表标记为真正食谱想要返回一个IEnumerable<Category>列表,其中包括所有的食谱IsCompanyRecipe == true

回答

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

您不需要将布尔值与真/假比较 –

+3

尽管显式比较有时会增加代码的可读性,在这种情况下,或在复杂的表达式 –

+0

Clarity是IMO的关键。 –