简单示例子查询Linq [英] Simple Example Subquery Linq

查看:74
本文介绍了简单示例子查询Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

T-SQL查询

Select * from dbo.User_Users
Where UserID IN (Select UserID from Course_Enrollments)

上述查询的LINQ to Entities替代

LINQ to Entities alternative of Above Query

var innerquery = from en in Course_Enrollments
select en.UserID;

var query = from u in User_Users
where innerquery.Contains(u.UserID)
select u;

stackoverflow上有很多复杂的子查询,我只想看一个简单的例子,说明如何通过linq完成一个简单的子查询.

There are alot of complex subqueries on stackoverflow, i just want to see a simple example of how a simple subquery is done via linq.This is how i done it, however its not good because it sends 2 queries to the database.

推荐答案

简单的答案是使用 "let" 关键字并生成一个支持您的条件查询的子查询为主要实体设置.

Simple answer is use the "let" keyword and generate a sub-query that supports your conditional set for the main entity.

var usersEnrolledInCourses = from u in User_Users
                                 let ces = from ce in Course_Enrollments
                                           select ce.UserID
                                 where ces.Contains(u.UserID)
                             select u;   

这将在TSQL中创建类似于以下的存在块

This will create an exists block in TSQL similar to

SELECT [Extent1].*
   FROM dbo.User_Users AS Extent1
   WHERE EXISTS (SELECT 1 AS [C1]
                     FROM dbo.Course_Enrollements AS Extent2
                     WHERE (Extent2.UserID = Extent1.UserId))

它接近您的要求,通常会在SQL Server上创建相同的查询计划.

It's close to what you've asked for and will generally create the same query plan on SQL Server.

希望这会有所帮助!

这篇关于简单示例子查询Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆