First recognized as Linq to Entity, first recognized as linqtoentity

Source: Internet
Author: User

First recognized as Linq to Entity, first recognized as linqtoentity

Background: C #. Net MVC and I have been developing it for nearly one and a half years. I have been doing it for a long time but I have not summarized it. This is an opportunity to write what I understand. -- The following content is based on others' articles

Technical introduction:

LINQ (Language Integrated Query) is a group used for C # and VB.. NET Language extension, which allows you to write C # Or VB.net code and operate memory data in the same way as querying databases. LINQ provides rich query syntaxes similar to SQL, which are powerful and easy to use. The summary shows the official implementation set of the LINQ technology:

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:

 

Concept logic:

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:

var user = new User();

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 var user = new User()2 {3     ID = Guid.NewGuid(),4     Account = "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:

var user = 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 class UserExt2 {3     public static void Drink(this User user, object water)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:

var user = 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. It is not an accident, but Microsoft intends to make it easier for programmers familiar with SQL. 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.Users4                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 (var db = new EntityContext())2 {3     var roles = 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:

var user = db.Users.Where(o => o.Roles != null);

The corresponding standard query operator expression is:

1 var users = from o in db.Users2             where o.Roles != null3             select o;
Ii. projection operators

The projection operator Select is similar to the SELECT clause in SQL. IT projects an object as an anonymous instance to control 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:

var users = db.Users.Select(o => new { o.Account, o.Password });

The corresponding standard query operator expression is:

1 var users = from o in db.Users2             select 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:

var users = 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:

var users = 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:

var users = 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:

var users = 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:

var users = db.Users.OrderBy(o => o.Roles.Count);

The corresponding standard query operator expression is:

1 var users = from o in db.Users2             orderby o.Roles.Count3             select o;

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:

var users = db.Users.OrderByDescending(o => o.Roles.Count);

The corresponding standard query operator expression is:

1 var users = from o in db.Users2             orderby o.Roles.Count descending3             select o;

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:

var users = db.Users.GroupBy(o => o.Roles.Count);

The corresponding standard query operator expression is:

1 var users = from o in db.Users2             group o by o.Roles.Count into g3             select 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:

var roles = 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:

var roles = 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:

var roles = 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:

var roles = user1.Roles.Except(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:

var user = 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:

var user = 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:

var user = 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:

var result = 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:

var result = 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:

var result = 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:

var result = 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:

var result = 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:

var result = 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:

var result = 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:

var result = 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.

The article is easy to understand and comprehensive, and more is to record yourself for your convenience.

 

Related Article

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.