将Linq转换为SqlCommand

本文关键字:SqlCommand 转换 Linq | 更新日期: 2023-09-27 18:27:40

这个Linq查询在SQL Server中的等价物是什么?

IEnumerable<Profile> profiles = am.Profile.Where(a => articles.Select(b => b.ProfileId).Distinct().Contains(a.ProfileID));

其中articles为:

IEnumerable<Article> articles = (from a in am.Article
                                 orderby a.AddedDate descending
                                 select a).ToList();

将Linq转换为SqlCommand

使用EXISTS:

SELECT * FROM Profile P
WHERE EXISTS(
    SELECT 1 FROM Article A
    WHERE A.ProfileId = P.ProfileId
)

除此之外,您的linq查询效率低下。为什么在Contains之前使用Distinct?在使用Contains之前,没有必要删除重复项。

这更具可读性和效率:

IEnumerable<Profile> profiles = am.Profile
    .Where(p => articles.Any(a => a.ProfileID == p.ProfileID));
SELECT * FROM Profile
WHERE
EXISTS(SELECT DISTINCT ProfileId FROM Article WHERE ProfileId in (SELECT ProfileID FROM  Profile)) 
Select p.*
From [Profile] p
Where p.profileID In (
    Select Distinct ProfileId
    From [Article]
)