Entity Framework Technology series 7: LINQ to entities

Source: Internet
Author: User
Preface

LINQ (Language Integrated Query) is a group of extensions for C # and VB. NET languages. It allows you to write C # Or VB. NETCodeTo operate the memory data in the same way as the query database. 7: LINQ to entities in the series of Entity Framework technology provides a wide range of SQL-like Query syntaxes, which are powerful and easy to use. The summary shows the official implementation set of the LINQ technology:

 

Figure1OfficialLINQImplementation of a summary chart

As shown in, LINQ to entities is an implementation of the LINQ Technology in the object model. It forms a combination of LINQ to ADO. Net with LINQ to SQL and LINQ to datasets. LINQ to entities can generate esql and support querying the service layer of the Entity Framework using the LINQ syntax. Demonstrate the technical details of the LINQ to entities consumption Entity Data Model:

 

Figure2LINQ to entitiesMap to the Object Data Model

 

Related Concepts

Before you begin to learn about the functions of LINQ to entities, you need. net Framework 3.5 and later versions will explain several extensions of the C # language, which helps us understand the principles and implementations of the LINQ to entities technology more easily and deeply.

1. implicitly instantiate local variables

After. NET Framework 3.5, the syntax for instantiating local variables has a new option: use the "Var" keyword for implicit typing:

 
VaRUser =NewUser ();

The implicit typed syntax is similar to the syntax for declaring variables in Javascript. It can simplify the syntax for instantiating local variables to a certain extent. However, if implicit instantiation is used only for this purpose, this article will not specifically mention it. Implicit typing is more important to use for the instantiation of anonymous types.

Note that only partial variable instantiation allows the implicit instantiation syntax. This means that private variable instantiation cannot enjoy this benefit. At the same time, it is not allowed to use the implicit instantiation syntax to declare only variables or if the instantiated object is null.

Ii. object initialization

Object initialization refers to the assignment of object attributes when an object is instantiated:

1 VaRUser =NewUser ()2 {3Id =Guid. newguid (),4Account ="Apollo"5};
Iii. Anonymous type

The SELECT statement of LINQ to entities can project the object type to the anonymous type, so it is necessary to briefly introduce the anonymous type. An anonymous type indicates a type that meets the requirements of the context. Because this type is temporary, you do not need to name it. The Declaration syntax of the anonymous type is as follows:

VaRUser =New{Id = guid. newguid (), name ="Apollo"};
Iv. Extension methods

The extension method is a syntactic sugar created by Microsoft to expand existing frameworks.. NET Framework 3.5 implements upgrade and extension of. NET Framework 2.0 through many extension methods. The extension method is amazing. The extended object can be expanded in behavior without knowing the existence of the extension method. The extension method is also very poor. If you do not know it, you may not know that the object has an extension behavior; or you may know that there is an extension method, but I don't know which extension library to REFERENCE TO MAKE IT support the extension behavior. The syntax of the extension method is as follows:

1 Public Static ClassUserext2 {3Public Static VoidDrink (ThisUser user,ObjectWater)4 {5 ...6 }7}
5. Lambda expressions

Lambda expressions are developed by Delegate and anonymous methods. They can assign expressions or code blocks (anonymous methods) to a variable to encode the expression with a minimum amount of input. Lambda expressions are generally used with the static Extension Method of ienumerable <t> to complete quick query of object sets. The syntax of lambda expressions is as follows:

 
VaRUser = dB. Users. firstordefault (O => O. Account ="Apollo");
Vi. standard query Operators

The system. LINQ. enumerable static class declares a set of standard query operators (sqo. The syntax of the standard query operator is very similar to that of the standard SQL. This is not an accident, but Microsoft intends to make it familiar with the SQLProgramIt is easier for staff to get started. The basic syntax of the standard query operator is as follows:

 1   Using ( VaR DB = New  Entitycontext ())  2  {  3       VaR Roles = From O In  DB. Users  4                  Where O. Account = "  Apollo  "  5                  Select  O. roles;  6   ...  7 }

Standard query operators are closely related to lambda expressions. The compiler converts an appeal expression to the following sequence of explicit extension method calls with Lambda expressions as parameters:

 
1 Using(VaRDB =NewEntitycontext ())2 {3VaRRoles = dB. Users. Where (O => O. Account ="Apollo"). Select (O =>O. Roles );4}

 

Standard query operator

Next, we will introduce the classification of standard query operators such as conditional query, projection, partition, sorting, grouping, set, element, quantifiers, and aggregation commonly used in data query operations.

I. Conditional Operators

The where clause is similar to the WHERE clause in SQL. It is used for conditional query. The following Extension Method Expression queries the user set that meets the condition "the role is not blank:

 
VaRUser = dB. Users. Where (O => O. roles! =Null);

The corresponding standard query operator expression is:

 
1 VaRUsers =FromOInDB. Users2WhereO. roles! =Null3SelectO;
Ii. projection operators

The projection operator select is similar to the select clause in SQL. IT projects an object as an anonymous instance and controls the properties of the objects displayed or processed by the specified query iterator. In addition, it should be noted that the select operator in the extension method expression is not necessary. In the omitted mode, the complete projected object will be returned. The following extension expression projects the user's account and password information into an anonymous type:

VaRUsers = dB. Users. Select (O =>New{O. Account, O. Password });

The corresponding standard query operator expression is:

 
1 VaRUsers =FromOInDB. Users2Select New{O. Account, O. Password };
Iii. Partition Operators

Partition operators are used to partition objects. The take operator is similar to the top operator in SQL. The following extension method expressions return the first five user objects:

 
VaRUsers = dB. Users. orderby (O => O. roles. Count). Take (5);

The Skip operator is used to skip a specified number of objects and return the remaining objects in the sequence. The following extension method expressions return the remaining users except the first 10 outdoor users:

VaRUsers = dB. Users. orderby (O => O. roles. Count). Skip (10);

The takewhile operator is used to return the adjacent element set when the condition expression value is true. The following Extension Method Expression returns all user sets before the first user with three roles:

 
VaRUsers = dB. Users. orderby (O => O. roles. Count). takewhile (O => O. roles. Count =3);

The skipwhile operator is used to skip the element when the condition expression value is true and return the remaining element sets. The following Extension Method Expression returns all user sets after the first user with three roles:

 
VaRUsers = dB. Users. orderby (O => O. roles. Count). skipwhile (O => O. Roles =3);
Iv. Sorting Operators

The sorting operator can sort objects by orderby, orderbydescending, thenby, thenbydescending, and reverse. The orderby operator is equivalent to the order by ASC clause in SQL. The following extension method expressions are used to sort objects in ascending order based on the number of roles they own:

VaRUsers = dB. Users. orderby (O => O. roles. Count );

The corresponding standard query operator expression is:

 
1 VaRUsers =FromOInDB. Users2OrderbyO. roles. Count3SelectO;

The orderbydescending operator is used to sort objects in descending order, which is equivalent to the order by DESC clause in SQL. The following extension method expressions enable users to sort objects in descending order based on the number of roles they own:

 
VaRUsers = dB. Users. orderbydescending (O => O. roles. Count );

The corresponding standard query operator expression is:

1 VaRUsers =FromOInDB. Users2OrderbyO. roles. Count descending3SelectO;

The thenby, thenbydescending, and reverse operators can only be used for iorderedenumerable interface objects. Therefore, they are generally used immediately after the orderby/orderbydesending operator methods. The thenby operator is translated by the compiler into a re-call to the orderby operator; the thenbydescending operator is translated by the compiler into a re-call to the orderbydescending operator; the reverse operator is used to sort objects in reverse order. Here we will not give an example here.

5. grouping operators

The Group operator groupby is similar to the group by clause in SQL to implement object grouping. The following extension expression groups user objects by their roles:

 
VaRUsers = dB. Users. groupby (O => O. roles. Count );

The corresponding standard query operator expression is:

1 VaRUsers =FromOInDB. Users2 Group O by O. roles. Count into G3Select New{Rolecount = G. Key, group = g };
Vi. Set Operators

The Set operators include distinct, union, intersect, and distinct T. Except distinct, the other three operators can combine two sequences into one. Similar to the distinct keyword in SQL, the distinct operator is used to delete objects with duplicate values in a sequence. The following extension expression deletes duplicate roles in a user role:

 
VaRRoles = user. roles. Distinct ();

Similar to the Union keyword in SQL, the Union operator is used to obtain the union of two sequences with the same structure. The following extension expression combines roles owned by user 1 and user 2 into a role set and removes duplicate roles:

VaRRoles = user1.roles. Union (user2.roles );

The Intersect operator is similar to the Intersect keyword in SQL, used to find the intersection of two sequences with the same structure. The following extension expression returns a set of roles that both user 1 and user 2 have:

 
VaRRoles = user1.roles. Intersect (user2.roles );

The distinct t operator is similar to the distinct T keyword in SQL. It is used to return a set of objects in the first sequence but not in the second sequence. The following extension expression returns a set of roles owned by user 1 but not owned by user 2:

 
VaRRoles = user1.roles. Role T (user2.roles );
VII. Element Operators

Element operators include two groups of operators, namely, the first, last, and single operators used to return a single object meeting the conditions from an ienumerable <t> sequence or to return an exception when no conditional object is met, and return the firstordefault, lastordefault, and singleordefault operators of null objects when a single object that meets the conditions or no objects that meet the conditions are not met. The first and firstordefault operators are used to return the first object that meets the conditions. The following Extension Method Expression returns the first user with three roles:

 
VaRUser = dB. Users. firstordefault (O => O. roles. Count =3);

The last and lastordefault operators are used to return the last object that meets the conditions. The following Extension Method Expression returns the last user with three roles:

 
VaRUser = dB. Users. lastordefault (O => O. roles. Count =3);

The single and singleordefault operators are used to return unique elements in a sequence that meets the conditions. If the sequence contains more than one element, an exception is thrown. The following Extension Method Expression returns the unique user whose account is "Apollo". If multiple user accounts are "Apollo", an exception is thrown:

 
VaRUser = dB. Users. singleordefault (O => O. Account ="Apollo");
8. quantifiers

The quantifiers include the any, all, and contains operators to check whether some or all objects in the sequence meet the conditions. The any operator is used to check whether any object in the sequence meets the conditions. The following Extension Method Expression returns true if any user has three roles. Otherwise, false is returned:

 
VaRResult = dB. Users. Any (O => O. roles. Count =3);

The all operator is used to check whether all objects in the sequence meet the conditions. The following Extension Method Expression returns true if all users have three roles; otherwise, false is returned:

 
VaRResult = dB. Users. All (O => O. roles. Count =3);

The contains operator is used to check whether the sequence contains the specified object. The following Extension Method Expression returns true if the set contains user 1; otherwise, false is returned:

 
VaRResult = dB. Users. Where (O => O. roles. Count =3). Contains (user1 );
9. Aggregation operators

Aggregation operators include count, Min, Max, sum, average, and other operators, used for statistical calculation of object sets. The Count operator is similar to the Count keyword in SQL. It is used to calculate the number of objects that meet the conditions in a sequence. The following extension method expressions return the number of users with three roles:

 
VaRResult = dB. Users. Count (O => O. roles. Count =3);

The min operator is similar to the min keyword in SQL and is used to return the minimum value calculated by condition. The following extension method expressions return the number of roles owned by the minimum number of users:

 
VaRResult = dB. Users. Min (O => O. roles. Count );

The max operator is similar to the max keyword in SQL and is used to return the maximum value calculated by condition. The following extension expression returns the number of roles owned by the most users:

 
VaRResult = dB. Users. Max (O => O. roles. Count );

The sum operator is similar to the sum keyword in SQL and is used to return the total number calculated by condition. The following Extension Method Expression returns the total number of roles that have been granted to the user:

 
VaRResult = dB. Users. sum (O => O. roles. Count );

The average operator is similar to the average keyword in SQL and is used to return the average value calculated by condition. The following extension expression is used to return the average number of roles owned by a user:

 
VaRResult = dB. Users. Average (O => O. roles. Count );

 

Summary

This article first provides the official implementation set of the LINQ technology, as well as the technical details of the implementation of the LINQ to entities, and then briefs several basic concepts related to the LINQ to entities; finally, the usage of standard query operators commonly used by LINQ to entities is classified. It can also be seen that the functions of LINQ to entities and SQL are basically one-to-one.

Next articleArticleThe Design and Implementation of an RBAC model will be completed by using all the technologies described above in this series.

 

Attachment download: PDF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.