LINQ表达式组合/连接

时间:2016-04-28 13:46:13

标签: c# entity-framework linq join

我正在开发一个食谱管理器程序,首先使用Entity Framework 6代码。我在数据库中有以下实体:

public class Item {
    [DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]        
    public int ItemId { get; set; }

    [Required]
    public string ItemName {get; set; }

    // Other properties
}

public class Recipe {
    [DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]
    public int RecipeId { get; set; }

    [Required]
    public string RecipeName { get; set; }

    public virtual ICollection<Ingredient> Ingredients { get; set; }

    // Other properties
}

public class Ingredient {
    [Key, Column( Order = 0 )]
    public int RecipeId { get; set; }

    [ForeignKey( "RecipeId" )]
    public virtual Recipe Recipe { get; set; }

    [Key, Column( Order = 1 )]
    public int ItemId { get; set; }

    [ForeignKey( "ItemId" )]
    public virtual Item Item { get; set; }

    public double Quantity { get; set; }

    // Other properties
}

public class Meal {
    [DatabaseGenerated( DatabaseGeneratedOption.Identity ), Key]        
    public int MealId { get; set; }

    [Required]
    public string MealName {get; set; }

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

    public virtual IEnumerable<Ingredient> Ingredients() {
        if ( Recipes == null )
            yield break;

        foreach ( var recipe in Recipes )
            foreach ( var ingredient in recipe.Ingredients )
                yield return ingredient;
    }
}

我的问题是Ingredients类中的Meal属性。那里的代码将返回制作膳食所需的所有成分的列表,但我想返回一个组合列表。也就是说,如果餐中的一个配方需要2个鸡蛋而另一个需要1个鸡蛋,则返回鸡蛋的两个条目。我想要退回一个3个鸡蛋的条目。

我可以使用LINQ表达式来组合这些吗?相当于:

的东西
SELECT item.ItemName, SUM(ing.Quantity)
FROM Meals AS m
JOIN RecipeMeals AS rm ON m.MealId = rm.Meal_MealId
JOIN Ingredients AS ing ON rm.Recipe_RecipeId = ing.RecipeId
JOIN Items AS item ON ing.ItemId = item.ItemId
GROUP BY item.ItemName

2 个答案:

答案 0 :(得分:0)

试试这个

var result = from m in Meals
    join rm in RecipeMeals on m.MealId equals rm.Meal_MealId
    join ing in Ingredients on rm.Recipe_RecipeId equals ing.RecipeId
    join item in Items on ing.ItemId equals item.ItemId
    group ing by item.ItemName into g
    select new { g.Key, g.Sum(p => p.Quantity) }

答案 1 :(得分:0)

如果您定义了导航属性(并且确实拥有它们),那么它非常简单 - 无需考虑连接,只需“导航”就好像它们是对象一样。 EF将为您生成必要的SQL连接。

等效的LINQ to Entities查询是这样的:

fgets(message, 50, stdin); /* read one line from the standard input */
/* remove newline character */
{
    char* lf /* declare a variable */
        = strchr(message, '\n'); /* and initialize it with the pointer to the first '\n' in the string message */
    if (lf != NULL) /* check if '\n' is found */
        *lf = '\0'; /* if found, replace '\n' with '\0' and delete the newline character (and string after '\n', which won't usually present) */
}