LinQ--Integrated Query language

Source: Internet
Author: User

LinQ to SQL
LinQ-Integrated Query language.
The LINQ Language integration query (Language Integrated query) is a set of extensions for the C # and Visual Basic languages.
it allows writing C # or Visual Basic code to manipulate memory data in the same way as querying a database.
LinQ to sql--querying SQL Server database
LinQ to object--querying a collection in memory

ORM thought: O-r-M
Object objects--entity classes
Relation relational database--tables in the database
Mapping mapping--the classes and tables, fields and columns.

LINQ generates the structure of entity classes:
1. Generate a DataContext class. Corresponds to the bridge between the program memory and the hard disk database.
2. Generate a series of instance classes that correspond to the table one by one.
3. Each entity class has a property that corresponds to a column in the table (the property of a value type is nullable type bool?). Int? Double?)
Int? a=null;//can be an empty type
System.nullable<bool> _sex;
System.nullable<system.datetime> _birthday;
4. The association between tables and tables in the database is transformed into member variables in the in-memory class.

One, increase
1. Building Objects
2. Say a word to the context
3.context Submission
Cases:
Create a bridge between a memory object and a database
Mydbdatacontext context = new Mydbdatacontext ();

First step: Create a physical object
Info data = new info ();
Data. Code = "p101";
Data. Name = "Zhang Fei";
Data. Sex = true;
Data. Nation = "n001";
Data. Birthday = new DateTime (1990, 3, 15);

Step two: Talk to the context, commit to it when you insert the action
Context.Info.InsertOnSubmit (data);

Step Three: Submit
Context. SubmitChanges ();

Second, delete
1. Find out from the database
2. Talk to the context, submit the time, delete
3. Submit

Create a bridge between a memory object and a database
Mydbdatacontext context = new Mydbdatacontext ();

The first step: Find the object you want to delete.
var query = from p in context. Info where P.code = = "p101" select P;
var query = Context.Info.Where (p = = P.code = = "P101");
Info data = query. First ();

Second step: Talk to the context, the submission of the time to delete this object.
Context.Info.DeleteOnSubmit (data);
Step Three: Submit
Context. SubmitChanges ();

Third, change
1. Find objects from the database to
2. Change the value of the object.
3. Submit to send it back.

Create a bridge between a memory object and a database
Mydbdatacontext context = new Mydbdatacontext ();

The first step: Find objects from the database to
var query = context.Info.Where (P=>p.code = = "p009");
Info data = query. First ();

Step Two: Change
Data. Name = "Tianqi";
Data. Sex = false;

Step Three: Submit
Context. SubmitChanges ();

Iv. Check
LINQ Statement Extension method

No conditions are queried for all var query = from p in context. Info select P;
Have conditions
Single
Equivalent var query = from p in context. Info where p.nation = = "n001" select P;
Unequal value var query = from p in context. Info where P.birthday < new DateTime (1990,.) Select P;
Many
With or var query = from p in context. Info where p.nation = = "n001" && p.sex==true select P;
Fuzzy
To.. Beginning
startswiths var query = from p in context. Work where P.firm.startswith ("China") select p;
To.. End
endswiths var query = from p in context. Work where P.firm.endswith ("line") select P;
Contains..
Contains () var query = from p in context. Work where P.firm.contains ("Inner Mongolia") select p;
Specify the location is ...
Substring (...) = = "value" var query = from p in context. Work where p.firm.substring (1, 1) = = "Country" select P;
var query = from p in context. Work where P.firm.startswith ("China") && P.firm.endswith ("line") select P;
Link queries and subqueries have syntax, but are seldom written.
You can directly manipulate the relationship object between objects, and LINQ will automatically generate the corresponding Connection statement or subquery statement for us.

var query=from p in context. Info where p.nation1.name== "Han" select p;

Sort:
Order BY property name Ascending var query = from p in context. Work P.startdate select P;
Order BY property name Descending descending var query = from p in context. Work p.startdate descending select p;

Extension methods:
()
OrderByDescending ()

Statistical functions.
Surround the LINQ statement and call the appropriate method
Count () var query = (from P in context. Info select P). Count ();
Sum (p=>p. Property name)
Average (p=>p. Attribute name)
Max (p=>p. Property name)
Min (p=>p. Property name)

Takes the first object of the collection.
First () Query.first ();


Paging query:
Skip (the number of bars to skip). Take (the condition to be taken out) var query = (from the p in context. Work select P). Skip (6). Take (3);

The statement can also be written like this:

var query = Context.Info.Where (p = = P.nation1.name = "Han"). Where (p = = P.sex = = False);

var query = Context.Info.Where (p = = P.nation1.name = "Han" && p.sex = = false);

var query = Context.Info.OrderBy (P=>p.birthday);

var query = context.Info.OrderByDescending (p = = p.birthday);

var query = Context.Info.Max (p = = p.birthday);


Set operation: intersection, and, poor
var q1 = context.Info.Where (p = p.nation! = "n001");
var q2 = Context.Info.Where (p = = P.sex = True);

Intersection: var query = Q1. Intersect (Q2);
Set: var query = Q1. Union (Q2);
Difference set: var query = Q1. Except (Q2);

Practice:

Public partial class default4:system.web.ui.page{Private Const int PageSize = 3;//defines a constant, the number per page is private Mydbdata    Context _context = new Mydbdatacontext (); Fill full page drop-down list private void Fillpage () {//Get total number of pages int rowscount = _context.        Car.count ();//number of synthetic lines int pagecount = Convert.ToInt32 (math.ceiling (1.0*rowscount/pagesize)); Populate the drop-down list for (int i = 0; i < PageCount; i++) {ListItem li = new ListItem ((i + 1).            ToString (), i.tostring ());        DdlPage.Items.Add (LI); }}//Displays the car data for the specified page private void Showcar () {var query = _context. Car.skip (PageSize * Convert.ToInt32 (Ddlpage.selectedvalue)).        Take (PageSize);        Repeater1.datasource = query;        Repeater1.databind (); The number of pages displayed Lblall.        Text = DdlPage.Items.Count.ToString (); LbL.    Text = DdlPage.SelectedItem.Text; } protected void Page_Load (object sender, EventArgs e) {if (! IsPostBack) {Fillpage();        Showcar ();    }}//drop-down list protected void Ddlpage_selectedindexchanged (object sender, EventArgs e) {showcar ();        }//home protected void Btnfirst_click (object sender, EventArgs e) {ddlpage.selectedindex = 0;    Showcar (); }//Last protected void Btnend_click (object sender, EventArgs e) {//ddlpage.selectedindex = Convert.ToInt32 (1.0 * _context.        Car.count ()/PageSize)-1;        Ddlpage.selectedindex = ddlpage.items.count-1;    Showcar ();        }//previous page protected void Btnprev_click (object sender, EventArgs e) {if (ddlpage.selectedindex<=0)            {Showcar (); Btnprev.        Enabled = false;            } if (ddlpage.selectedindex>0) {ddlpage.selectedindex--;            Showcar (); Btnprev.        Enabled = true; }}//next page protected void Btnnext_click (object sender, EventArgs e) {if (ddlpage.selectedindex& Lt;ddlpage.iTEMs.            Count-1) {ddlpage.selectedindex++;        Showcar (); }    }}

1. Create an interface:

2. Create an info Class (partial): facilitates direct invocation of attributes

PublicPartial class Info{public string Sexname {get {return Sex.value = = true?        "Male": "Female";        }} public string Nationname {get {return nation1.name; }} public string firm {get {if (this). work.count>0) {work data= work.orderbydescending (P = p.orders).               First (); return data.            Firm;            } else {return "none"; }}} public string Depart {get {if (this). work.count>0) {Work data = this. Work.orderbydescending (p = p.orders).                First (); return data.            Depart;            } else {return "none"; }}} public string Father {get {if (this). Family.count > 0)//family relationship exists {var query = this. Family.where (p = p.title= = "T001"); if (query. Count () > 0)//have father this item is filled in with {return query. First ().                Name;                } else {return "null";            }} else {return "none"; }}} public string Mother {get {if (this). family.count>0) {var query = this.                Family.where (p=>p.title== "T002"); if (query. Count () >0) {return query. First ().                Name;                } else {return "null";            }} else {return "none"; }}} public string couple {get {if (this). family.count>0) {var query = this.                Family.where (p=>p.title== "T003"); if (query. Count () >0) {return query. First ().                Name;                } else {return "null";            }} else {return "none"; }        }    }}

3. Home: Binding Data

Private Mydbdatacontext _context = new Mydbdatacontext ();    private void Showinfo ()    {        repeater1.datasource = _context.info;        Repeater1.databind ();    }    protected void Page_Load (object sender, EventArgs e)    {        if (! IsPostBack)        {            showinfo ();        }    }

LinQ--Integrated Query language

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.