📜  Entity Framework-投影查询

📅  最后修改于: 2020-11-21 07:25:56             🧑  作者: Mango


LINQ到实体

理解LINQ to Entities的最重要概念之一是它是一种声明性语言。重点在于定义所需的信息,而不是如何获取信息。

  • 这意味着您可以花费更多的时间来处理数据,而花费更少的时间来尝试找出执行诸如访问数据库之类的任务所需的基础代码。

  • 重要的是要理解,声明性语言实际上并没有从开发人员那里删除任何控件,但是它有助于开发人员将注意力集中在重要的内容上。

LINQ to实体基本关键字

了解用于创建LINQ查询的基本关键字很重要。仅需记住几个关键字,但是您可以通过各种方式将它们组合以获得特定的结果。以下列表包含这些基本关键字,并提供了每个关键字的简单说明。

Sr. No. Keyword & Description
1

Ascending

Specifies that a sorting operation takes place from the least (or lowest) element of a range to the highest element of a range. This is normally the default setting. For example, when performing an alphabetic sort, the sort would be in the range from A to Z.

2

By

Specifies the field or expression used to implement a grouping. The field or expression defines a key used to perform the grouping task.

3

Descending

Specifies that a sorting operation takes place from the greatest (or highest) element of a range to the lowest element of a range. For example, when performing an alphabetic sort, the sort would be in the range from Z to A.

4

Equals

Used between the left and right clauses of a join statement to join the primary contextual data source to the secondary contextual data source. The field or expression on the left of the equals keyword specifies the primary data source, while the field or expression on the right of the equals keyword specifies the secondary data source.

5

From

Specifies the data source used to obtain the required information and defines a range variable. This variable has the same purpose as a variable used for iteration in a loop.

6

Group

Organizes the output into groups using the key value you specify. Use multiple group clauses to create multiple levels of output organization. The order of the group clauses determines the depth at which a particular key value appears in the grouping order. You combine this keyword with by to create a specific context.

7

In

Used in a number of ways. In this case, the keyword determines the contextual database source used for a query. When working with a join, the in keyword is used for each contextual database source used for the join.

8

Into

Specifies an identifier that you can use as a reference for LINQ query clauses such as join, group, and select.

9

Join

Creates a single data source from two related data sources, such as in a master/detail setup. A join can specify an inner, group, or left-outer join, with the inner join as the default. You can read more about joins at msdn.microsoft.com

10

Let

Defines a range variable that you can use to store subexpression results in a query expression. Typically, the range variable is used to provide an additional enumerated output or to increase the efficiency of a query (so that a particular task, such as finding the lowercase value of a string, need not be done more than one time).

11

On

Specifies the field or expression used to implement a join. The field or expression defines an element that is common to both contextual data sources.

12

Orderby

Creates a sort order for the query. You can add the ascending or descending keyword to control the order of the sort. Use multiple orderby clauses to create multiple levels of sorting. The order of the orderby clauses determines the order in which the sort expressions are handled, so using a different order will result in different output.

13

Where

Defines what LINQ should retrieve from the data source. You use one or more Boolean expressions to define the specifics of what to retrieve. The Boolean expressions are separated from each other using the && (AND) and || (OR) operators.

14

Select

Determines the output from the LINQ query by specifying what information to return. This statement defines the data type of the elements that LINQ returns during the iteration process.

投影

投影查询仅通过从数据库中检索特定字段来提高应用程序的效率。

  • 拥有数据后,您可能需要根据需要进行投影或过滤,以在输出之前对数据进行整形。

  • 任何LINQ to Entities表达式的主要任务是获取数据并将其提供为输出。

本章的“开发LINQ to Entities查询”部分演示了执行此基本任务的技术。

让我们看一下下面的代码,其中将检索学生列表。

using (var context = new UniContextEntities()) {

   var studentList = from s in context.Students select s;

   foreach (var student in studentList) {
      string name = student.FirstMidName + " " + student.LastName;
      Console.WriteLine("ID : {0}, Name: {1}", student.ID, name);
   }
}

单一物件

要检索单个学生对象,可以使用First()或FirstOrDefault枚举方法,该方法返回序列的第一个元素。 First和FirstOrDefault之间的区别在于,如果没有提供的条件的结果数据,则First()将引发异常,而如果没有结果数据,则FirstOrDefault()将返回默认值null。在下面的代码片段中,将从列表中找到第一个学生的名字叫阿里。

using (var context = new UniContextEntities()) {

   var student = (from s in context.Students where s.FirstMidName 
      == "Ali" select s).FirstOrDefault();

   string name = student.FirstMidName + " " + student.LastName;
   Console.WriteLine("ID : {0}, Name: {1}", student.ID, name);
}

您还可以使用Single()或SingleOrDefault获取单个学生对象,该对象返回序列的单个特定元素。在以下示例中,检索到一个ID为2的学生。

using (var context = new UniContextEntities()) {

   var student = (from s in context.Students where s.ID 
      == 2 select s).SingleOrDefault();
   string name = student.FirstMidName + " " + student.LastName;
    
   Console.WriteLine("ID : {0}, Name: {1}", student.ID, name);
   Console.ReadKey();
}

对象清单

如果要检索名字为Ali的学生列表,则可以使用ToList()枚举方法。

using (var context = new UniContextEntities()) {

   var studentList = (from s in context.Students where s.FirstMidName 
      == "Ali" select s).ToList();

   foreach (var student in studentList) {
      string name = student.FirstMidName + " " + student.LastName;
      Console.WriteLine("ID : {0}, Name: {1}", student.ID, name);
   }

   Console.ReadKey();
}

订购

要以任何特定顺序检索数据/列表,可以使用orderby关键字。在以下代码中,将按升序检索学生的摘要列表。

using (var context = new UniContextEntities()) {

   var studentList = (from s in context.Students orderby
      s.FirstMidName ascending select s).ToList();

   foreach (var student in studentList) {
      string name = student.FirstMidName + " " + student.LastName;
      Console.WriteLine("ID : {0}, Name: {1}", student.ID, name);
   }

   Console.ReadKey();
}

标准与投影实体框架查询

假设您有一个包含ID,FirstMidName,LastName和EnrollmentDate的Student模型。如果要返回学生列表,则标准查询将返回所有字段。但是,如果您只想获取包含ID,FirstMidName和LastName字段的学生列表。在这里应该使用投影查询。以下是投影查询的简单示例。

using (var context = new UniContextEntities()) {

   var studentList = from s in context.Students
      orderby s.FirstMidName ascending
      where s.FirstMidName == "Ali"

   select new {s.ID, s.FirstMidName, s.LastName};

   foreach (var student in studentList) {
      string name = student.FirstMidName + " " + student.LastName;
      Console.WriteLine("ID : {0}, Name: {1}", student.ID, name);
   }

   Console.ReadKey();
}

上面的投影查询不包括EnrollmentDate字段。这将使您的应用程序更快。