[10 days to learn about Linq to SQL] The next day -- data context

Source: Internet
Author: User

Directory

[10 days to learn about Linq to SQL] day 1-Basic Knowledge [10 days to learn about Linq to SQL] The next day -- data context [10 days to learn about Linq to SQL] The third day -- Data Query

[10 days to learn about Linq to SQL] the fourth day -- Data Update

[10 days to learn about Linq to SQL] day 6-Stored Procedure

DataContext = data context

The DataContext type (data context) is System. data. the important types in the Linq namespace are used to translate query syntaxes into SQL statements, and return data from the database to the caller and write entity modifications to the database.

DataContext provides the following functions:

L log the SQL statements generated by DataContext

L execute SQL statements (including query and update statements)

L create and delete Databases

DataContext is a bridge between entities and databases. First, we need to define entities mapped to data tables.

------------This part of content is explained in Baidu encyclopedia and msdn, and can be temporarily ignored by new users;

Define object classes

No matter what architecture, we can't do without the construction of entity classes. If we simply try SQL queries, the returned data processing can make us exhausted;

 

[Copy part of LoveCherry]

using System.Data.Linq.Mapping; [Table(Name = "Customers")]public class Customer{    [Column(IsPrimaryKey = true)]    public string CustomerID {get; set;}    [Column(Name = "ContactName")]    public string Name { get; set; }    [Column]    public string City {get; set;}}

Taking the Northwind database as an example, the preceding MERs class is mapped into a table corresponding to the Customers table in the database. Three attributes are defined in the type, which correspond to the three fields in the table. The CustomerID field is the primary key. If the Column attribute is not specified, the system uses the attribute Name as the field Name of the data table. That is to say, the attribute Name of the object class must be the same as the field Name in the data table.

Now, create an ASP. NET page, add a GridView control to the page, and use the following code to bind data:

Using System. data. linq; DataContext ctx = new DataContext ("server = xxx; database = Northwind; uid = xxx; pwd = xxx"); Table <Customer> MERs = ctx. getTable <Customer> (); GridView1.DataSource = from c in mers MERs where c. customerID. startsWith ("A") select new {customer ID = c. customerID, customer name = c. name, city = c. city}; GridView1.DataBind ();

Use the DataContext type to associate the object class with the data in the database. You can define the connection string directly in the DataContext constructor, or use IDbConnection:

using System.Data.SqlClient; IDbConnection conn = new SqlConnection("server=xxx;database=Northwind;uid=xxx;pwd=xxx");DataContext ctx = new DataContext(conn);

Then, get the Table Type of the underlying data Table through GetTable. Obviously, the Customers Table entity in the database is of the Customer type. The subsequent query syntax can be understood even if you do not understand SQL. Find the record whose mermerid starts with "A" from the MERs table, and encapsulate CustomersID, Name, and City into A new anonymous type to return it.

The result is as follows:

 

Strong typeDataContext

public partial class NorthwindDataContext : DataContext {     public Table<Customer> Customers;     public NorthwindDataContext(IDbConnection connection) : base(connection) { }     public NorthwindDataContext(string connection) : base(connection) { } }

Strong data context makes the code more concise:

NorthwindDataContext ctx = new NorthwindDataContext ("server = xxx; database = Northwind; uid = xxx; pwd = xxx"); GridView1.DataSource = from c in ctx. customers where c. customerID. startsWith ("A") select new {customer ID = c. customerID, customer name = c. name, city = c. city}; GridView1.DataBind ();

DataContext encapsulates many practical functions.

Log feature

 

Using System. IO; NorthwindDataContext ctx = new NorthwindDataContext ("server = xxx; database = Northwind; uid = xxx; pwd = xxx"); StreamWriter sw = new StreamWriter (Server. mapPath ("log.txt"), true); // Append ctx. log = sw; GridView1.DataSource = from c in ctx. customers where c. customerID. startsWith ("A") select new {customer ID = c. customerID, customer name = c. name, city = c. city}; GridView1.DataBind (); sw. close ();

After running the program, log.txt is recorded in the website directory. Each query appends the following logs to a text file:

SELECT [t0].[CustomerID], [t0].[ContactName], [t0].[City] FROM [Customers] AS [t0] WHERE [t0].[CustomerID] LIKE @p0 -- @p0: Input String (Size = 2; Prec = 0; Scale = 0) [A%] -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.20706.1

To put it simply:

  • 1. The data context is a cash machine;

  • 2. I took the credit card to get the money, and it threw it out to me (Query data);

  • 3. Deposit withdrawal records in the Bank (Log feature);

  • 4. Sometimes there is a lot of money, and you must take the money to save it, that is, put the money into the ATM, and my credit card will be rich (Add data);

  • 5. If you accidentally lose your mobile phone one day, you need to change the phone number. After the change, you must go to the bank to change the bound mobile phone number of your credit card. Otherwise, you cannot receive the notification (Update Data)

  • 6. If one day I am so poor that I can't afford my credit card, I can't, but I can only sell my cards (Delete data);

 

The above understanding should be very simple ~~~ Poor distance ~~

This article was originally compiled by CoolHots. for reprinting, please keep the link: [10 days to learn Linq to SQL] The next day-data context

Home page: CoolHots technology sharing

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.