. NET two ways to access the database (C # language ),

Source: Internet
Author: User

. NET two ways to access the database (C # language ),

1. directly use C # To operate the Database Class Library ADO. NET
ADO. NET uses the Connection object to connect to the database, and uses Command or DataAdapter
And return the execution result to DataReader or DataAdapter.
Then use the obtained DataReader or DataAdapter object to operate the data results.

Ii. Entity Framework
Entity FrameworkIs An ORM framework of Microsoft. Is to support data-oriented software development
Send applications. We generally use this function in combination with linq and lambda expressions.

ORM (Object Relational Mapping Object relationship ing)It refers to the object-oriented object model and
Data Structures of relational databases are converted to each other. (Mutual conversion between table entities and tables)

LINQ Query: When we use the linq query, the definition will be adjusted to the Queryable class, that is
This class encapsulates all the query methods of linq and provides a set of query implementation IQueryable <T>
Static Method of the data structure.
IQueryable, like IList, is a collection used to receive a group of data, IQeurable
(IQuerable <T>) does not immediately create persistent data in the memory, but only traverses it (such as through
Foreach), convert it to List, and so on before loading data to the memory, it can achieve "deferred execution
Row. If the currently loaded object has an associated entity (associations), the associated entity can be
.

Ilist-the inheritance order is as follows:
Ilist-> ICollection-> IEnumerable
IEnumerable allows developers to define the implementation of the foreach statement function and supports non-generic method simplification.
Single Iteration
The same IQueryable inherits from IEnumerable <T>.

The Queryable class provides an extended basic query method: Where, Select
Select provides the following methods:
Public static IQueryable <TResult> Select <TSource, TResult> (this
IQueryable <TSource> source, Expression <Func <TSource, TResult>
Selector );
The method provided by where is as follows:
Public static IQueryable <TSource> Where <TSource> (this
IQueryable <TSource> source, Expression <Func <TSource, bool>
Predicate );
Public static IQueryable <TSource> Where <TSource> (this
IQueryable <TSource> source, Expression <Func <TSource, int, bool>
Predicate );

Lambda expressions

(1) designers of source. net found that when using the anonymous method,There is still some extra coding work for letters or words.

For example, the delegate keywordThis further simplifies the writing of anonymous methods.

(2) Use
List <int> arr = new List <int> () {1, 2, 3, 4, 5, 6, 7 };
Arr. ForEach (new Action <int> (delegate (int a) {Console. WriteLine
();}));
Arr. ForEach (new Action <int> (a => Console. WriteLine ()));
The code for the anonymous method is as follows:
Delegate (int a) {Console. WriteLine ();}
The code for using lambda expressions is as follows:
A => Console. WriteLine ()
Here, I will explain this lambda expression.
<1>
A is an input parameter. The compiler can automatically infer the type of a parameter,
If no parameter is input, you can write it as follows:
() => Console. WriteLine ("ddd ")
<2>
=> Is a lambda Operator
<3>
Console. WriteLine (a) is the statement to be executed.
You can use {} to package multiple statements.
If a return value is required, you can directly write the return statement.

LINQ
1. query Operators
(1) Origin
The. net designer defines a series of extension methods in the class library.
To help users operate on collection objects
These extension methods constitute the query operators of LINQ.
(2) Use
This series of extension methods, such:
Where, Max, Select, Sum, Any, Average, All, Concat, etc.
All are extended for IEnumerable objects.
That is to say, you can use these extension methods as long as the IEnumerable interface is implemented.
Let's take a look at this Code:
List <int> arr = new List <int> () {1, 2, 3, 4, 5, 6, 7 };
Var result = arr. Where (a =>{ return a> 3 ;}). Sum ();
Console. WriteLine (result );
Console. ReadKey ();
Two extension methods are used in this Code.
(3) Benefits
In the above Code
Arr. Where (a =>{ return a> 3 ;}). Sum ();
This sentence can be written as the following code:
(From v in arr where v> 3 select v). Sum ();
The execution details of the two statements are identical.
As you can see, the second code is more semantic and easier to understand.
In the second code, where is the query operator.
(4) Description of standard query Operators
<1> Filter
Where
Usage: arr. Where (a =>{ return a> 3 ;})
Description: finds the elements that meet the specified conditions in the set.
OfType
Usage: arr. OfType <int> ()
Filters elements in a set based on the specified type.
<2> projection
Select
Usage: arr. Select <int, string> (a => a. ToString ());
Note: Each element in the set is projected into a new set. In the preceding example, the new set is
A set of IEnumerable <String>
Selectworkflow
Usage: arr. selectiterator <int, string> (a => {return new
List <string> () {"a", a. ToString ()};});
Note: Each element of the sequence is projected into a sequence, and all sequences are finally projected.
Merge
<3> there are many query operators. Please refer to MSDN. I will start another article later.
Chapter describes all these operators.

2. query expression
(1) Origin
As mentioned above, the extension method represented by the query operator is used to operate the set;
Although it is very convenient, there are still deficiencies in readability and code semantics;
Therefore, the query expression is written.
Although this is similar to SQL statements, they are essentially different.
(2) Usage
From v in arr where v> 3 select v
This is a very simple query expression.
(3) Description:
First look at a piece of pseudo code:
From [type] id in source
[Join [type] id in source on expr equals expr [
SubGroup]
[From [type] id in source | let id = expr | where condition]
[Orderby ordering, ordering, ordering...]
Select expr | group expr by key
[Into id query]
<1> interpretation of the first line:
Type is optional,
Id is an item in the set,
Source is a collection,
If the type in the set is different from the type specified, the forced type conversion is triggered.
<2> explanation of the second line:
A query expression can contain 0 or more join clauses,
The source here can be a brand new set, which is not equal
Source
Expr can be an expression.
[Into subGroup] subGroup is an intermediate variable,
It inherits from IGrouping and represents a group, that is,
"Multiple"
You can use this variable to obtain the number of objects in this group and the number of objects in this group.
Key
For example:
From c in db. MERs
Join o in db. Orders on c. CustomerID
Equals o. CustomerID into orders
Select new
{
C. ContactName,
OrderCount = orders. Count ()
};
<3> explanation of the third line:
One query expression can contain one or more from clauses.
A query expression can contain 0 or more let clauses, and the let clause can create
Temporary Variables
For example:
From u in users
Let number = Int32.Parse (u. Username. Substring
(U. Username. Length-1 ))
Where u. ID <9 & number % 2 = 0
Select u
A query expression can contain 0 or more where clauses. The where clause can
To specify query Conditions
<4> explanation of the fourth line:
A query expression can have 0 or more sorting methods.
Each sorting method is separated by commas (,).
<5> interpretation of the fifth line:
A query expression must end with select or group.
Select followed by the content to be retrieved
Group by is used to group the retrieved content.
For example:
From p in db. Products
Group p by p. CategoryID into g
Select new {g. Key, NumProducts = g. Count ()};
<6> interpretation of Row 6:
The last into clause plays a role in
Use the result of the preceding statement as the data source for subsequent statement operations
For example:
From p in db. Employees
Select new
{
LastName = p. LastName,
TitleOfCourtesy = p. TitleOfCourtesy
} Into EmployeesList
Orderby EmployeesList. TitleOfCourtesy ascending
Select EmployeesList;

 

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.