【问题标题】:How can I convert Sql query to Linq and its equivalent with Join() method in Entity Framework Core如何将 Sql 查询转换为 Linq 及其在 Entity Framework Core 中的 Join() 方法的等价物
【发布时间】:2020-07-09 12:32:06
【问题描述】:
select
a.*
from
Article a join
ArticleTag at on a.Id = at.ArticleId join
Tag t on at.TagId = t.Id
where
t.Id=8
我还可以访问IQueryable<Article>、IQueryable<Tag>和IQueryable<ArticleTag>对象。
如何将此 Sql 查询转换为 Linq 及其在 Entity Framework Core 中的 Join() 方法和 lambda 表达式的等效项?
【问题讨论】:
标签:
c#
sql
linq
linq-to-sql
entity-framework-core
【解决方案1】:
var innerJoinQuery =
from a in Article
join at in ArticleTag on a.Id equals at.ArticleId
where at.TagId == 8
select a;
这是最高效的方式。如果您使用 LINQ 扩展,EF 可能会做一些棘手的“事情”
但如果你坚持...
var innerJoinResult =
Articles.Join(ArticleTags.Where(x => x.TagId == 8),
a => a.Id,
at => at.ArticleId,
(a, at) => a);
【解决方案2】:
假设你有 IQueryable articleTags,文章列表可以通过
articleTags.Where(a => a.Tag.id = 8).Select (a -> a.ArticleTag );