Introduction to Query expressions (LINQ)

Source: Internet
Author: User
Tags processing instruction xml attribute xslt sql getdate
  • LINQ is short for Language Integrated Query, which is integrated in. net.Programming Language. Has become an integral part of the programming language.ProgramThe compilation syntax check, rich metadata, smart sensing, static type, and other advantages can be obtained. In addition, it also enables queries to conveniently Query Information in the memory, not just external data sources.

    LINQ defines a set of standard query operators for all. in the programming language of the. NET platform, you can directly declare a unified method for cross-, filtering, and projection operations. The standard query operator allows the query to act on all sources based on ienumerable <t> interfaces, it also allows third-party specific domain operators suitable for the target domain or technology to expand the standard query operator set. More importantly, third-party operators can use their own implementation of additional services to freely replace standard query operators. According to the Convention of the LINQ mode, these queries prefer the same language integration and tool support as standard query operators.

    There are five parts of LINQ to objects, LINQ to datasets, LINQ to SQL, LINQ to entities, and LINQ to XML.

    First, do not mention the C # features:

    1)Object set Initiator

    C #3.0 provides the object set initializer for you:

    Additional: At first, I thought this object set initializer may be a problem. If it is useless, I just need to reduce it a little bit.CodeSuch simple initialization work can be used by most code generators. Later, when studying the anonymous type, I suddenly found that, without this object initializer, the anonymous type would be more complex? Or is it hard to implement? VaR test = new {key = "test", value = "test"}; What should I do if there is no object initializer?

    2)Anonymous and implicit local variables

    There are some types in C #, which are used as temporary data storage. The life cycle is only within this method, and the method ends, and the life cycle of this type is gone. Here we can use an anonymous type.

    VaR keypair = new {key = "Yuyi", value = "20 "};

    This keypair is an anonymous type. Note that keypair is a variable name, not a class name. Well, there is a var above. What is this? This is an implicit local variable in C #3.0.

    3)Extension Method

    1. The class of the method must be static.

    2. The method must also be static.

    3. The first parameter of the method must be the type you want to extend. For example, if you want to extend a method to int, the first parameter must be Int.

    4. You also need the this keyword before the first parameter.

    Follow the steps above for an instance:

    4) anonymous methods and lambda expressions

    C #2.0 provides an anonymous method for us:

    This. btnrefresh. Click + = delegate (Object sender, eventargs e) {binddata ();};

    Lambda expressions:

    Lambda operators are read as "goes to", followed by expressions or statement blocks (this is also different from anonymous methods. Anonymous methods can only use statement blocks but not expressions ), the following example shows the types of lambda expressions:

    // The type of X is omitted. the compiler can deduce it based on the context, followed by an expression.

    5) iterator

    C #2.0 has built-in support for the iterator. Let's look at the system. collections, system. collections. in the generic namespace, all sets implement this interface: ienumerable, which also has a generic version. Note that this interface has only one method: ienumerator getenumerator (); ienumerator is the iterator interface, and it also has a generic version.

    I,LINQ to objects

    As described above, the query operations in LINQ are extension methods added to the ienumerable interface (these methods are called query operators in LINQ ), then you can use linq in the method of method call:

    Note that none of the above methods operate ienumerable, and then return ienumerable objects. You can divide these methods into classes by purpose.

    Purpose

    Method

    Ing (ing the query results to the desired results)

    Select (2 reloads), selectloads (4 reloads)

    Conditional Filtering

    Where (two reloads), oftype (this method is extended to ienumerable. When using this method, you must include the generic parameter, books. oftype () means to traverse elements from the books set. If this element is of the book type or its subtype, add it to the return set)

    Sort (note that the sorting method is replaced by iorderedenumerable inherited from ienumerable)

    Orderby (two reloads), orderbydescending (two reloads), reverse (nothing else, that is, reverse the order of ienumerable), thenby, thenbydescending (these two are extension methods for iorderedenumerable, so they can only be used after orderby, and its function is to sort by a key in a sorted Series)

    Group

    Groupby (8 reloads) and tolookup (4 reloads. They are used to convert ienumerable into an ILookup object based on a key. This object will be grouped by key)

    Join

    Groupjoin, join

    Transformation

    Cast (LINQ can only operate on generic sets! Who told you that LINQ can only operate on generic sets? This method is to do this. It is a method for ienumerable extension. It converts an ienumerable into ienumerable, and then you can enjoy LINQ, for example, if I use arraylist to save a user set, arraylist users = new arraylist (); however, what is the where of LINQ and does not extend the interface ienumerable implemented by arraylist? Use cast: ienumerable myusers = users. Cast (); That's simple)

    Syntax of the query expression:

    Query of non-generic sets:

    The where and select methods in LINQ are all extended for ienumerable, while arraylist implements the iemerable interface. Don't worry. We have taken this into consideration for LINQ:

    The cast () method is an extension of ienumerable. It is dedicated to this transformation. It will traverse every element in a non-generic set, then convert it to the tresult type and return an ienumerable object. Then we can use other extension methods of LINQ. NOTE: If your non-generic set contains an element that cannot be converted to the tresult type, an exception is thrown. If there is a null element, no exception is thrown, the final element will also be null. Otherwise, use the oftype method:

    This method will only return elements of the "yes" tresult type in non-generic sets, and ignore other elements (this will not throw an exception ).

    II,LINQ to Datasets

    1) LINQ to dataset Overview

    Relatively speaking, LINQ to dataset is the smallest piece in The LINQ technology. Although it is an offline operation model extracted from the database, after all, the object is only an object in the memory. Therefore, most operations are the same as those of LINQ to object. The difference is that fields must be indicated according to the dataset and able structure. The following briefly lists some of the notes that need to be paid attention to compared to the special functions of LINQ to dataset.

    2) query untyped Dataset

    Compared with General LINQ, when the query object is untyped dataset, field and setfield are used to read and write different column fields. Below is a simple example:

    Pay attention to three points here

    1. because untyped dataset does not implement the interfaces of ienumerable and iqueryable, if you want to use it as a queryable object, you must first convert it with asenumerable () or asqueryable, only the iqueryable or iqueryable object can be converted to ienumerable. For example, from o in orders. asenumerable ()

    2. generally, field ("column A") and setfield ("column A") are used to read and write the elements corresponding to different column fields. tables ["orders"]. compared to the access mode of row ["ROWA"] ["column A"], a major benefit is to avoid exceptions of the null type. When we used to retrieve data from dataset, if the obtained data is null, an exception is thrown. Therefore, we often perform operations similar to If (Ds. tables ["orders"]. row ["ROWA"] ["column A"]! = NULL), but field ("column A") can avoid this problem. Because field ("Column A") is nullable. This feature comes from the use of this generic type. For example, if you think it may be null when you take int data, you can use field ("column ") to avoid throwing an exception.

    3. The use of field and setfield is not limited to the query of LINQ. It can also be used elsewhere in the program. It can be used to replace the previous method for accessing dataset. For example:

    3) query Typed Dataset

    This is simpler. For dataset with a defined type, we can query it like an object in the memory. For example:

    Another difference from untyped dataset is that you do not need to use the conversion method like asenumerable () or asqueryable () When querying it. Because all the defined dataset inherit the base class typedtablebase, and this base class has implemented the interface of ienumerable

    4) Relation in query Dataset

    Sometimes there is relation in dataset, just like dB. For example, add relation to the following Dataset:

    If we want to access a table related to the table through relation in the same way as in LINQ to SQL, we can use the getchildrows method to obtain the datarows In the table associated with the current table, and return it as an iqueryable object that can be queried. For example:

    In this way, we can access the object table through relation.

    III,LINQ to SQL

    1) LINQ to SQL instance

    Step 1: Create a database mark language (dbml. Database description language, a document in XML format used to describe the database) file. Taking the northwind database as an example, the preceding MERs class is mapped into a table that corresponds to the customers table in the database.

    Step 2: Create an ASP. NET page and add a gridview control to the page

    Step 3: write code for Data Binding

    Step 4: run the displayed result.

    2) entry-level instances

    A) create a ing:

    B) Execute the query:

    When executing the above insert operation, you will certainly encounter an exception. This is because the postid of the data table field corresponding to the ID is the primary key of the table. You should not assign a value during the insert operation, some people say that I did not assign a value to the post ID attribute when instantiating an object,. net will assign the id value to 0 in the background, so you need to modify the ing object:

    This attribute is not only required for the primary key of the data table. If you set the default value in the database, you do not need to use it when inserting data using a program, for example, createdate.

    C) insert an object:

    D) update data:

    During the update process, you must first query the object from the database, modify the attributes of the object, and then update the object to the database:

    E) delete data:

    With insert and update, a delete curd is missing for the query. For Delete, you only need to call the deleteonsubmit method of table. This will not be detailed here.

    3) advanced class instance

    Like SQL statements, the following two methods are supported:

    1. Use the WHERE clause to search for two tables

    2. Use the join clause

    First obtain the object of the post and blog table, and then apply the operation:

    The following are the SQL statements generated for us by using LINQ to SQL. We can see from the above that the join conditions are implemented using the WHERE clause. This join method is not recommended, in the standard of ANSI-82 SQL, the recommended way is to use the join clause:

    One-to-one relationship:

    4) Examples of configuration methods supported by LINQ to SQL

    Configuration in pure attribute mode:

    1. autosync: automatic synchronization. This attribute is an enumeration type.

    Autosync. Default: Automatically Selected. This is the default value. It is usually synchronized when the column has a default value in the database and the isdbgenerated attribute of column is marked as true.

    Autosync. Always, always synchronous

    Autosync. Never, never sync

    Autosync. oninsert is synchronized after the insert operation is executed. As in the example in our blog Park, the blog ID is the primary key, auto-incrementing, and we do not provide it when inserting the database, instead, it is automatically generated by the database. How can we synchronize this ID after inserting our class at this time?

    Autosync. onupdate, synchronized during update

    Example: in fact, we can see how this autosync affects the behavior of LINQ to SQL. Let's execute insert post:

    Check the generated SQL code:

    Under the insert code, we will also see a select code that returns the postid and createdate values to the query, but we have not executed the query operation. It turns out that autosync is causing bad results, by default, columns whose isdbgenerated is true will be returned. To check whether it is correct, I will modify the post title attribute:

    [Column (autosync = autosync. Always)] Public String title {Get; set ;}

    Then execute the above insert code to see what the generated SQL will do:

    The generated SELECT statement also returns the title.

    Now you should understand the significance of autosync. You can test it one by one.

    2. canbenull

    This attribute can specify whether the columns in the corresponding database table are allowed to be null. If this column cannot be null, an exception is triggered when you assign null to this attribute. But remember, null does not mean that it is an empty string or zero. For more information about null, see the masterpiece of anytao.

    3. dbtype

    If you want to use the createdatabase method of datacontext to create a database table from the ing Class, you 'd better specify this so that you can explicitly specify what dbtype your column is in the database table, otherwise, LINQ to SQL will deduce dbtype from the attribute type, which may not be very suitable. For example, this string type:

    [Column (dbtype = "nvarchar (50) not null")] Public String title {Get; set ;}

    We can also create a database from the ing Class. It is said that the ORM is dominated by O. But in practice, we always create a database first and then create an object based on the database, so this is not rom. From the information here, You can first design domain objects, establish relationships between objects, and finally use the createdatabase method to create database tables. More information about createdatabase will be further described later.

    4. Expression

    I can only say that it is too thoughtful to write data into SQL. Expression is used to represent a computing column. What does it mean? This attribute is obtained by computing the columns in the database table. For example, if the price column in our database stores USD, we need to use RMB to represent this attribute:

    [Column (expression = "price * 6")] public float price {Get; set ;}

    The above example is only used to describe the purpose of the expression attribute, and the practice in this example is really not desirable. For the Exchange Rate Problem of converting the US dollar to the renminbi, the exchange rate fluctuates at any time, so it is hard coded like this, it's really bad. After reading it, you will get a smile.

    5. isdbgenerated

    It can be seen from the name that the value of this attribute is generated by the database and does not need to be assigned by our program, such as this auto-increment column, for example, this column has a default value (time, we can use the SQL getdate () function to set the value, instead of being specified in the Program)

    6. isprimarykey

    Is it a primary key? If so, you need to specify this attribute. If your primary key is composed of multiple columns, add these attributes. The primary key will be further introduced later.

    7. isversion and updatecheck

    These two will not be mentioned here. There will be a large introduction later. This column feature is inherited from the abstract feature data. It inherits two attributes:

    8. Name

    This is used when your attribute name is inconsistent with this column name.

    9. Storage

    Sometimes, complicated business logic is applied to the set in your attribute, while the value of LINQ to SQL is retrieved from the database and assigned to this attribute, this set is used by default. In this case (the attribute assigned to the class by the database value), you do not want to execute the logic in this set, you want to direct this value to the private field behind the property:

    10. Association

    This feature is used to establish the relationship between entities. In the previous example, we saw:

    Association has two most important attributes: thiskey and otherkey.

    Thiskey is used to identify the key associated with other objects. If it is not specified, isprimarykey is identified on the attributes of this class. Otherkey is used to define the key of the associated class. If it is not specified, the ID column of the associated class is used.

    The Association feature is also inherited from the data feature, and also has the name and storage attributes. The storage attribute is the same as the column attribute. Here, the name attribute is used to establish a link when the ing Class is used to dynamically create a database. This name is the link name.

    XML file configuration method:

    You may find that the datacontext class has several overloaded constructors, which we commonly use:

    Datacontext (string fileorconnectionstring );

    There is also one:

    Datacontext (string fileorconnectionstring, mappingsource Mapping );

    What is this mappingsource? In the system. Data. LINQ. Mapping namespace, you will find such a relationship:

    You may be able to guess the names of its two subclass. We used attributemappingsouce as the attriing configuration file. In addition, XML can be used as the ing configuration file, as shown in the figure above, there are several static methods for xmlmappingsource. They can build xmlmappingsource instances using various forms of XML data sources:

    Xmlmappingsource mapping = xmlmappingsource. fromxml (file. readalltext (@ "E:" cnblogs "map. xml"); datacontext dbcontext = new datacontext (connectionstring, Mapping );

    We can use XML for ing to construct a datacontext object in this way.

    UseVisual StudioThe designer generates the ing configuration code.

    After all, we are accompanied by vs all day, so it is quite enjoyable to use a visual tool.

    You only need to create a new LINQ to SQL classes type item in your project, drag the table from the server browser to the design interface, and then use the tool in the toolbar, the relationship between the tables is OK.

    Vs generates three files for us: a file suffixed with dbml (in fact, this file is an XML file, it is similar to the file format that just used XML for ing configuration.) a c # code file is a local class, which is compiled into a class together with the dbml file, this is similar to aspx in Asp.net and its background code. There is also a suffix named layout, which is used by the designer to store the positions of tables in the designer on the interface and has nothing to do with our program. Ssssss

    I will not introduce the use of the visual designer here. I will do it myself, and then I will see what is in the several generated files, plus the detailed explanation of the manual operations, I want to understand this will be easy.

    IV,LINQ to XML

    1. Overview of the LINQ to XML class

    A) xattribute class

    Xattribute indicates an XML Attribute.

    B) xcdata class

    Xcdata indicates a CDATA text node.

    C) xcomment class

    Xcomment indicates an XML comment.

    D) xcontainer class

    Xcontainer is an abstract base class applicable to all nodes that may have subnodes. The following classes are derived from the xiner iner class: xelement, xdocument

    E) xdeclaration class

    Xdeclaration indicates an XML declaration. The XML declaration is used to declare the encoding of the XML version and document. In addition, the XML Declaration also specifies whether the XML document is an independent document.

    F) xdocument class

    Xdocument indicates an XML document.

    G) xdocumenttype class

    Xdocumenttype indicates an XML document type definition (DTD ).

    H) xelement class

    Xelement indicates an XML element. For details and examples,

    I) xname class

    Xname indicates the name of the element (xelement) and attribute (xattribute. For details and examples, LINQ to XML is designed to make the XML name as simple as possible. XML names are generally considered as high-level topics in XML due to their complexity. There is evidence that this complexity is not caused by namespaces that are often used by developers for programming, but by namespaces prefixes. Using the namespace prefix can reduce the number of clicks required for XML input or make XML more readable. However, the prefix is usually a shortcut that uses the complete XML namespace, which is not required in most cases. By parsing all prefixes into the corresponding XML namespace, LINQ to XML simplifies the XML name. If necessary, you can use the getprefixofnamespace method to use the prefix. You can control the namespace prefix if necessary. In some cases, if you are using another XML system (such as XSLT or XAML), you need to control the namespace prefix. For example, if an XPATH expression uses the namespace prefix embedded in An XSLT style table, make sure that the XML document is serialized using a namespace prefix that matches the prefix used in the XPath expression.

    J) xnamespace class

    Xnamespace indicates the namespace of xelement or xattribute. A namespace is a component of xname.

    K) xnode class

    Xnode is an abstract class that represents the nodes in the XML tree. The following classes are derived from the xnode class:

    Xtext, xcontainer, xcomment, xprocessinginstruction, xdocumenttype

    Xnodedocumentordercomparer class

    Xnodedocumentordercomparer provides the document Sequence Function for comparing nodes.

    Xnodeequalitycomparer class

    Xnodeequalitycomparer provides the function to compare whether the node values are equal.

    L) xobject class

    Xobject is the abstract base class of xnode and xattribute. It provides annotation and event functions.

    M) xobjectchange class

    Xobjectchange specifies the event type when an xobject event is triggered.

    N) xobjectchangeeventargs class

    Xobjectchangeeventargs provides data for changing and changed events.

    O) xprocessinginstruction class

    Xprocessinginstruction indicates an XML Processing Instruction. The Processing Command passes the information to the XML processing application.

    P) xtext class

    Xtext indicates a text node. This type is not required in most cases. This class is mainly used for mixed content.

    Q) xdocument class

    The xdocument class contains the information required for a valid XML document. These include XML declarations, processing instructions, and annotations. Note that if you need specific functions provided by the xdocument class, you only need to create an xdocument object. In many cases, xelement can be used directly. Directly Using xelement is a simple programming model. Xdocument is derived from xiner iner. Therefore, it can contain subnodes. However, the xdocument object can have only one child xelement node. This reflects the XML standard, that is, there can be only one root element in the XML document.

    R) xelement class

    The xelement class is one of the basic classes in LINQ to XML. It represents an XML element. You can use this class to create elements, change element content, add, change, or delete child elements, add attributes to elements, or serialize Element Content in text format. It can also interoperate with other classes in system. XML (such as xmlreader, xmlwriter, and compiledtransform.

    2. query, update, and delete

    Search for elements with specific attributes

    XML tree modification and function construction in memory

    Modifying the XML tree in place is a traditional method to change the XML document shape. Typical applications load documents to data storage areas (such as Dom or LINQ to XML); Use programming interfaces to insert nodes, delete nodes, or change node content; save the XML file or transmit it over the network.

    LINQ to XML allows another method that can be used in many scenarios: function construction. The function structure regards data modification as a conversion problem, rather than a specific operation in the data storage area. If you use a Data Representation and effectively convert it from one form to another, the result is equivalent to using a data storage area and performing operations on it in a certain way to adopt another shape. The key to the function constructor is to pass the query results to the xdocument and xelement constructor.

    This example assumes that you want to modify the following simple XML document to change attributes to elements. This section describes the traditional local modification methods. Then, the function constructor is displayed. XML file:

    You can write some process code to create elements from the attributes and then delete the attributes, as shown below:

    Function Constructor

    In contrast, function methods include code used to form a new tree, selecting elements and attributes from the source tree, and performing corresponding conversions when adding them to the new tree. The function method is as follows:

    In this example, the function example is neither shorter nor simpler than the first example. But if you want to make a lot of changes to an XML tree, the non-function method will become very complex and clumsy. In contrast, when using function methods, you only need to form the required XML and embed appropriate queries and expressions to extract the required content. The code generated by function methods is easier to maintain. Note that in this example, the execution of function methods may not be better than that of tree operation methods. The main problem is that the function method creates more short-lived objects. However, if the function method can improve the programmer's efficiency, the compromise is also an effective method. This is a simple example, but it shows the fundamental differences between the two methods. Function Methods can generate higher efficiency gains for conversion of large XML documents.

    Add elements, attributes, and nodes to the XML tree

    The following method adds sub-content to xelement or xdocument:

    The following method adds the content as a peer node of xnode. The most common node for adding peer content to a node is xelement. However, you can also add valid peer content to other types of nodes, such as xtext or xcomment.

    Modify elements, attributes, and nodes in the XML tree

    The following table lists the methods and properties that can be used to modify an element, a child element of an element, or an attribute ). The following method modifies xelement.

    Remove elements, attributes, and nodes from the XML tree

    You can modify the XML tree to remove elements, attributes, and other types of nodes. It is easy to remove a single element or attribute from an XML document. However, to remove a set of multiple elements or attributes, you must first convert a set into a list and then delete the corresponding elements or attributes from the list. The best way is to use the remove extension method, which can implement this operation. The main reason for this is that most of the collections retrieved from the XML tree are generated with delayed execution. If you do not first embody the set as a list, or do not use the extension method, you may encounter some bugs.

    Example: This example shows three methods for removing elements. First, remove a single element. Second, retrieve the collection of elements by using the enumerable. tolist <(of <(tsource>)> operator, and then remove the collection. Last, retrieve the collection of elements and use the remove extension method to remove the elements.

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.