0

我的数据库中有一张名为 Dish 的表和一张名为 Ingredient 的表。我还有另一个名为 DishIngredient 的表,它表示菜与成分或菜之一之间的关系。在 DishIngredient 中,我还有一个名为“table”的列,用于存储菜肴与菜肴之间或菜肴与配料之间的关系。

这是我的 C# 代码:

List<int> dish = (from x in db.DishIngredient
                  join y in db.Dish on x.dish_ing_dish equals y.dish_id
                  where x.dish_ing_ing == ing_id && x.table == "Ingredient"
                  select y.dish_id).ToList();

for (int i = 0; i < dish.Count; i++)
{
    int dish_id = dish[i];
    List<int> dish_in_dish = (from x in db.DishIngredient
                              join y in db.Dish on x.dish_ing_dish equals y.dish_id
                              where x.dish_ing_ing == dish_id && x.table == "Dish"
                              select y.dish_id).ToList();
    dish.AddRange(dish_in_dish);
}

dish = dish.Distinct().ToList();

我有一种感觉,我可以通过在 Dish 和 Dish 之间进行连接来获得相同的结果,我只是不知道该怎么做。

这段代码可以用 Dish 和 Dish 之间的连接重写吗?我也希望减少时间,什么会更快?

4

1 回答 1

0

我相信你可以通过加入来做到这一点,但我仍然不是很擅长它们,这会将你的数据库调用减少到 2 而不是 N+1:

List<int> dish = (from x in db.DishIngredient
                  join y in db.Dish on x.dish_ing_dish equals y.dish_id
                  where x.dish_ing_ing == ing_id && x.table == "Ingredient"
                  select y.dish_id).ToList();

List<int> dish_in_dish = (from x in db.DishIngredient
                              join y in db.Dish on x.dish_ing_dish equals y.dish_id
                              where dish.Contains(x.dish_ing_ing) && x.table == "Dish"
                              select y.dish_id).ToList();

dish = dish.Union(dish_in_dish).ToList();

这也可能有效:

List<int> dish = (from x in db.DishIngredient
    join y in db.Dish on x.dish_ing_dish equals y.dish_id
    where x.dish_ing_ing == ing_id && x.table == "Ingredient"
    select y.dish_id).Union(
        (from x in db.DishIngredient
        join y in db.Dish on x.dish_ing_dish equals y.dish_id
        join a in db.DishIngredient on a.dish_ing_ing equals x.dish_id
        join b in db.Dish on a.dish_ing_dish equals b.dish_id
        where x.dish_ing_ing == ing_id && x.table == "Ingredient"
        and a.table=="Dish"
        select b.dish_id).ToList();
于 2013-07-15T07:47:15.813 回答