【发布时间】:2019-12-27 13:15:55
【问题描述】:
我正在尝试使用 Entity Framework Core 执行左连接,但它在连接中创建了一个不起作用的子查询。
我创建了一个sample project 来说明问题
这是我的 Linq 查询,它从一个帐户中选择所有流以及该流期间的订阅者
Linq 查询语法
from account in context.Accounts
where account.Id == 6
join steam in context.Streams on account.Id equals steam.AccountId
join subscription in context.Subscriptions on account.Id equals subscription.TargetAccountId into
groupJoin
from subscription in groupJoin.Where(subscription => subscription.Date > steam.StreamStart && subscription.Date < steam.StreamEnd).DefaultIfEmpty()
select new {account, steam, subscription};
Linq 扩展方法语法
context.Accounts.Where(account => account.Id == 6)
.Join(context.Streams, outer => outer.Id, inner => inner.AccountId,
(account, stream) => new { Account = account, Stream = stream })
.GroupJoin(context.Subscriptions, outer => outer.Account.Id, inner => inner.TargetAccountId,
(outer, subscriptions) => new
{ Account = outer.Account, Stream = outer.Stream, Subscriptions = subscriptions })
.SelectMany(x =>
x.Subscriptions.Where(subscription =>
subscription.Date > x.Stream.StreamStart && subscription.Date < x.Stream.StreamEnd)
.DefaultIfEmpty(),
(x, subscription) => new { x.Account, x.Stream, Subscription = subscription }).ToList();
这是生成的查询
SELECT account."Id", account."Name", stream."Id", stream."AccountId", stream."StreamEnd", stream."StreamStart", stream."Title", t."SourceAccountId", t."TargetAccountId", t."Date"
FROM "Accounts" AS account
INNER JOIN "Streams" AS stream ON account."Id" = stream."AccountId"
LEFT JOIN (
SELECT "inner"."SourceAccountId", "inner"."TargetAccountId", "inner"."Date"
FROM "Subscriptions" AS "inner"
WHERE ("inner"."Date" > stream."StreamStart") AND ("inner"."Date" < stream."StreamEnd")
) AS t ON account."Id" = t."TargetAccountId"
WHERE account."Id" = 6
这给了我以下错误
Npgsql.PostgresException (0x80004005): 42P01: 无效引用 表“流”的 FROM 子句条目
我的 Linq 查询是错误的还是实体框架中的错误/限制?
【问题讨论】:
-
错误/限制。您使用的是什么 EF Core(查看它是否已在更高版本中修复或如何解决它)?
-
我正在使用 Npgsql.EntityFrameworkCore.PostgreSQL 2.2.4
-
注意:尽量避免保留/关键字(日期,内部)即使Postgres允许它们,您的框架也可能被它们触发。
标签: c# postgresql linq entity-framework-core