在我的数据库模式中,我有一个实体A,它与一定数量的其他实体E1,E2,...,En有关系。所有这些关系都是通过N个单独的联接表实现的,这些联接表包含A的ID和每个Ei的ID作为外键。我想做的是在LINQ中编写查询,该查询在单个查询中执行A与每个Ei的内部联接。在SQL中,查询如下所示
示例:
我们有一个Activity表,该表通过联接表Activity_ActivityCluster和Activity_ActivityEdition与ActivityCluster和ActivityEdition有关系。
with tmp0 as (
select t1."Id" as "ActivityId", t1."CreatedDate" as "ActivityCreatedDate", t1."Title" as "ActivityTitle",
t2."Id" as "ActivityEditionId",t2."CreatedDate" as "ActivityEditionCreatedDate",t2."Date" as "ActivityEditionDate"
from "Activity" t1, "Activity_ActivityEdition" jt, "ActivityEdition" t2
where t1."Id" = jt."ActivityId" and t2."Id" = jt."ActivityEditionId"
order by t1."Id"),
tmp1 as (
select t1."Id" as "ActivityId", t1."CreatedDate" as "ActivityCreatedDate", t1."Title" as "ActivityTitle",
t2."Id" as "ActivityClusterId", t2."CreatedDate" as "ActivityClusterCreatedDate", t2."Title" as "ActivityClusterTitle", t2."Description" as "ActivityClusterDescription"
from "Activity" t1, "ActivityCluster_Activity" jt, "ActivityCluster" t2
where t1."Id" = jt."ActivityId" and t2."Id" = jt."ActivityClusterId"
order by t1."Id")
select distinct tmp0."ActivityId",tmp0."ActivityEditionId",tmp1."ActivityId",tmp1."ActivityClusterId"
from tmp0 full outer join tmp1 on false
该查询的结果如下(我删除了一些行并对表进行排序以使其更具可读性,但我实际上不需要查询中的排序):
https://i.stack.imgur.com/0qVdT.png
我想做的是生成具有相同行为的Linq查询。我尝试了两个子查询,然后将结果合并到一个元组中,但问题是Linq为每个子查询生成了单独的查询,并将它们分别发送到数据库。
问题: 是否可以在Linq中编写一个行为与提供的SQL查询等效的单个查询,或者,如果只能通过使用子查询来实现,是否有办法防止Linq生成如此多的子查询,单独发送到数据库?我们正在使用.NET core 2.1