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的更多相关文章

  1. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  2. Entity Framework Tutorial Basics(22):Disconnected Entities

    Disconnected Entities: Before we see how to perform CRUD operation on disconnected entity graph, let ...

  3. Entity Framework Tutorial Basics(15):Querying with EDM

    Querying with EDM: We have created EDM, DbContext, and entity classes in the previous sections. Here ...

  4. Entity Framework Tutorial Basics(3):Entity Framework Architecture

    Entity Framework Architecture The following figure shows the overall architecture of the Entity Fram ...

  5. 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 ...

  6. Entity Framework Tutorial Basics(43):Download Sample Project

    Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...

  7. 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 ...

  8. Entity Framework Tutorial Basics(41):Multiple Diagrams

    Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...

  9. Entity Framework Tutorial Basics(37):Lazy Loading

    Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...

随机推荐

  1. (转)msys2使用教程

    一.安装 官方下载地址 http://www.msys2.org/ 指定好安装路径(一般D根目录即可),一路下一步就好. 二.配置国内镜像.设置窗体修改颜色 使用[清华大学开源软件镜像站]中的地址,修 ...

  2. 超简单tensorflow入门优化程序&&tensorboard可视化

    程序1 任务描述: x = 3.0, y = 100.0, 运算公式 x×W+b = y,求 W和b的最优解. 使用tensorflow编程实现: #-*- coding: utf-8 -*-) im ...

  3. 修改altibase MDB中的复制表的表结构

    前提条件:有MDB两个数据库,且知道普通用户和sys用户的密码等基本信息.操作:1:用sys用户登录isqlisql -s 127.0.0.1 -u sys -p manager -port 2030 ...

  4. 无状态服务 VS 有状态服务

    无状态服务 VS 有状态服务 https://blog.csdn.net/mysee1989/article/details/51381435 对服务器程序来说,究竟是有状态服务,还是无状态服务,其判 ...

  5. (转)通过WMI获取网卡MAC地址、硬盘序列号、主板序列号、CPU ID、BIOS序列号

    最近由于项目的需要,需要在程序中获取机器的硬盘序列号和MAC地址等信息,在C#下,可以很容易的获得这些信息,但是在C++程序中感觉比较麻烦.经过百度,发现很多大虾都是通过WMI来获取这些硬件信息的,网 ...

  6. HDU4825(字典树+贪心)

    Xor Sum Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 132768/132768 K (Java/Others)Total S ...

  7. 本地dns服务器到底是什么?有没有精确的概念?

    1.本地dns到底是什么?为什么有时候看到的本地dns的ip是局域网类型的ip? 有的人说本地dns的概念——————是运营商提供的dns, 有的人也说,是你的局域网里的路由器一类的设备里的dns. ...

  8. 【转】 Pro Android学习笔记(八五):了解Package(4):lib项目

    目录(?)[-] 什么是lib项目 小例子 Lib的实现 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.csdn.net/flowing ...

  9. Redis value的5种类型及常见操作

    Redis本身存储就是一个hash表,实际实࣫比hash表更复一些,后续讲存储结构时会细讲Key只有String类型Value包括String ,Set,List,Hash,Zset五中类型 STRI ...

  10. Debian7 apt源设置

    刚装完系统时是没有 apt-spy 的,这时候我们可以暂时先找个可用的源代替,如(写在 /etc/apt/sources.list 中): deb http://http.us.debian.org/ ...