Entity Framework Tutorial Basics(16):Linq-to-Entities Projection Queries
Linq-to-Entities Projection Queries:
Here, you will learn how to write LINQ-to-Entities queries and get the result entities. Visit LINQ Tutorials to learn LINQ step by step.
Projection is a process of selecting data in a different shape rather than a specific entity being queried. There are many ways of projection. We will now see some projection styling:
First/FirstOrDefault:
If you want to get a single student object, when there are many students, whose name is "Student1" in the database, then use First or FirstOrDefault, as shown below:
using (var ctx = new SchoolDBEntities())
{
var student = (from s in ctx.Students
where s.StudentName == "Student1"
select s).FirstOrDefault<Student>();
}
The above query will result in the following database query:
SELECT TOP (1)
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1]
WHERE 'Student1' = [Extent1].[StudentName]
The difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() returns default value (null) if there is no result data.
Single/SingleOrDefault:
You can also use Single or SingleOrDefault to get a single student object as shown below:
using (var ctx = new SchoolDBEntities())
{
var student = (from s in context.Students
where s.StudentID ==
select s).SingleOrDefault<Student>();
}
The above query would execute the following database query:
SELECT TOP (2)
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1]
WHERE 1 = [Extent1].[StudentID]
go
Single or SingleOrDefault will throw an exception, if the result contains more than one element. Use Single or SingleOrDefault where you are sure that the result would contain only one element. If the result has multiple elements then there must be some problem.
ToList:
If you want to list all the students whose name is 'Student1' (provided there are many students has same name) then use ToList():
using (var ctx = new SchoolDBEntities())
{
var studentList = (from s in ctx.Students
where s.StudentName == "Student1"
select s).ToList<Student>();
}
The above query would result in the following database query:
SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1]
WHERE 'Student1' = [Extent1].[StudentName]
go
GroupBy:
If you want to group students by standardId, then use groupby:
using (var ctx = new SchoolDBEntities())
{
var students = from s in ctx.Students
group s by s.StandardId into studentsByStandard
select studentsByStandard;
}
The above query would execute the following database query:
SELECT
[Project2].[C1] AS [C1],
[Project2].[StandardId] AS [StandardId],
[Project2].[C2] AS [C2],
[Project2].[StudentID] AS [StudentID],
[Project2].[StudentName] AS [StudentName],
[Project2].[StandardId1] AS [StandardId1]
FROM ( SELECT
[Distinct1].[StandardId] AS [StandardId],
1 AS [C1],
[Extent2].[StudentID] AS [StudentID],
[Extent2].[StudentName] AS [StudentName],
[Extent2].[StandardId] AS [StandardId1],
CASE WHEN ([Extent2].[StudentID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C2]
FROM (SELECT DISTINCT
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1] ) AS [Distinct1]
LEFT OUTER JOIN [dbo].[Student] AS [Extent2] ON ([Distinct1].[StandardId] = [Extent2].[StandardId]) OR (([Distinct1].[StandardId] IS NULL) AND ([Extent2].[StandardId] IS NULL))
) AS [Project2]
ORDER BY [Project2].[StandardId] ASC, [Project2].[C2] ASC
go
OrderBy:
If you want to get the list of students sorted by StudentName, then use OrderBy:
using (var ctx = new SchoolDBEntities())
{
var student1 = from s in ctx.Students
orderby s.StudentName ascending
select s;
}
The above query would execute the following database query:
SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1]
ORDER BY [Extent1].[StudentName] ASC
go
Anonymous Class result:
If you want to get only StudentName, StandardName and list of Courses for that student in a single object, then write the following projection:
using (var ctx = new SchoolDBEntities())
{
var projectionResult = from s in ctx.Students
where s.StudentName == "Student1"
select new {
s.StudentName, s.Standard.StandardName, s.Courses
};
}
The above query would execute the following database query:
SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent2].[City] AS [City]
FROM [dbo].[Student] AS [Extent1]
LEFT OUTER JOIN [dbo].[StudentAddress] AS [Extent2] ON [Extent1].[StudentID] = [Extent2].[StudentID]
WHERE 1 = [Extent1].[StandardId]
go
The projectionResult in the above query will be the anonymous type, because there is no class/entity which has these properties. So, the compiler will mark it as anonymous.
Nested queries:
You can also execute nested LINQ to entity queries as shown below:

The nested query shown above will result in an anonymous list with a StudentName and Course object.
SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Join1].[CourseId1] AS [CourseId],
[Join1].[CourseName] AS [CourseName],
[Join1].[Location] AS [Location],
[Join1].[TeacherId] AS [TeacherId]
FROM [dbo].[Student] AS [Extent1]
INNER JOIN (SELECT [Extent2].[StudentId] AS [StudentId], [Extent3].[CourseId] AS [CourseId1], [Extent3].[CourseName] AS [CourseName], [Extent3].[Location] AS [Location], [Extent3].[TeacherId] AS [TeacherId]
FROM [dbo].[StudentCourse] AS [Extent2]
INNER JOIN [dbo].[Course] AS [Extent3] ON [Extent3].[CourseId] = [Extent2].[CourseId] ) AS [Join1] ON [Extent1].[StudentID] = [Join1].[StudentId]
WHERE 1 = [Extent1].[StandardId]
go
In this way, you can do a projection of the result, in the way that you would like the data to be.
Entity Framework Tutorial Basics(16):Linq-to-Entities Projection Queries的更多相关文章
- Entity Framework Tutorial Basics(1):Introduction
以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...
- Entity Framework Tutorial Basics(22):Disconnected Entities
Disconnected Entities: Before we see how to perform CRUD operation on disconnected entity graph, let ...
- Entity Framework Tutorial Basics(15):Querying with EDM
Querying with EDM: We have created EDM, DbContext, and entity classes in the previous sections. Here ...
- Entity Framework Tutorial Basics(3):Entity Framework Architecture
Entity Framework Architecture The following figure shows the overall architecture of the Entity Fram ...
- Entity Framework Tutorial Basics(4):Setup Entity Framework Environment
Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...
- Entity Framework Tutorial Basics(43):Download Sample Project
Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...
- Entity Framework Tutorial Basics(42):Colored Entity
Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...
- Entity Framework Tutorial Basics(41):Multiple Diagrams
Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...
- Entity Framework Tutorial Basics(37):Lazy Loading
Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...
随机推荐
- WordPress 中文图片 上传 自动重命名
由于国人很少有在上传图片前将图片名重命名为英语的,所以自动重命名对于WP来说尤为重要,特别是LINUX的不支持中文名的. WordPress上传多媒体的代码都存放于\wp-admin\includes ...
- [SP16580]QTREE7
luogu vjudge 题意 一棵树,每个点初始有个点权和颜色(输入会给你) 0 u :询问所有u,v路径上的最大点权,要满足u,v路径上所有点的颜色都相同 1 u :反转u的颜色 2 u w :把 ...
- java 连接oracle数据库
package shujuku; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Prepared ...
- Makefile中的路径
使用 $(shell pwd) 可以在Makefile中指定为当前Makefile所在目录的路径
- Linux基础命令-文本文件查看工具
文本文件查看工具 cat concatenate 文本文件查看工具 cat /etc/fstab cat [OPTION]... [FILE]... -n:给显示的文本行编行 -E:显示行结束符 ta ...
- 开启 intel vt-d
1.开机后按“DEL”或“F2”进入BIOS: 2.在Advanced选项页中找到System Agent Configuration并选择进入: 3.进入System Agent Configura ...
- JSP Servlet中的Request和Response的简单研究
本文参考了几篇文章所得,参考目录如下: 1.http://www.cnblogs.com/guangshan/p/4198418.html 2.http://www.iteye.com/problem ...
- WPF案例:如何设计历史记录查看UI
(CSDN博客目前不支持外链, 只能纯文字) 设计WPF的UI,一般遵循下面的步骤: 1.首先分析数据结构 2.根据数据结构选择合理控件 3.定制外观 具体对于历史记录查看UI, 我们可以得知: 1. ...
- Windows_Server_2008远程桌面多用户登陆的配置方法
开启远程桌面后,Windows Vista(或Windows 2008)下默认只支持一个administrator用户登陆,一个登录后另一个就被踢掉了,下面提供允许同一个用户名同时多个用户登录的配置方 ...
- 2015.3.5 VS2005调用VC6 dll 时结构参数的传递
结构只能以地址方式进行传递,dll只能传递结构不能传递类 VS端: [DllImport(@"D:\程序\VC程序\MfcDllspace\Debug\space.dll")] p ...