与 EFCore 和 C# 5.0 的多对多关系:如何从两个表中获取字段

Many-To-Many relationships with EFCore and C# 5.0 : how to get the fields from the both of tables

我在 PostgreSQL 中有以下数据库 编辑:PizzaTopping 中有一个 Unique Key,它使用 Id_Pizza、Id_Topping

字段构建

如您所见,这是一个多对多关系。

当我要求 Linqpad 6 从我的数据库搭建脚手架时,我得到以下结果:

当我使用 EFCore Power Tools 要求他们对我的数据库进行逆向工程时,我得到了同样的结果。

我从各种来源阅读后发现,要让 EFCore 获取比萨饼配料列表,我应该这样做:

Pizzas.Where(p=>p.Description=="Margherita")
      .Include(p=>p.PizzaToppings)
      .ThenInclude(p=>p.IdToppingNavigation)

查询 EFCore 5 returns 此查询:

SELECT P."Id_Pizza",
       P."Description",
       T0."Id_PizzaTopping",
       T0."Id_Pizza",
       T0."Id_Topping",
       T0."Id_Topping0",
       T0."Description"
FROM "Pizza" AS P
LEFT JOIN
    (SELECT P0."Id_PizzaTopping",
            P0."Id_Pizza",
            P0."Id_Topping",
            T."Id_Topping" AS "Id_Topping0",
            T."Description"
     FROM "PizzaTopping" AS P0
     INNER JOIN "Topping" AS T ON P0."Id_Topping" = T."Id_Topping") AS T0 ON P."Id_Pizza" = T0."Id_Pizza"
WHERE P."Description" = 'Margherita'
ORDER BY P."Id_Pizza",
         T0."Id_PizzaTopping",
         T0."Id_Topping0"

因为我想 return 一个比萨饼的列表,顶部像:

margherita, mozzarella
margherita, tomato sauce
marinara, garlic
marinara, tomato sauce

我尝试添加 .Select(topping=>topping.description) 但它得到了披萨描述。

那么我如何获取浇头描述他们在浇头中的身份 table? 我试图在 .ThenInclude() 之后放置一个 .Select() 但我仍然看到 Pizza 实体并且 p.PizzaToppings 不包含 属性 对浇头的描述 table.

在这种情况下,您不需要 IncludeSelectMany 具有自定义投影:

var query = 
   from p in Pizzas
   from pt in p.PizzaToppings
   select new 
   {
      Pizza = p.Description,
      Topping = pt.IdToppingNavigation.Description
   }