LINQ to SQL 用於資料庫連接的DataContext對象成員

來源:互聯網
上載者:User

本篇博文接上一篇,DataContext類位於System.Data.Linq.dll程式集中的System.Data.Linq名稱空間下。在LINQ to SQL中負責實體物件和呢資料庫之間的資料交換及其他資料庫操作,還負責吧資料庫中的資料對應成實體類的執行個體。

DataContext是LINQ to SQL操作實體類建立後緊接著需要操作的對象。本文總結其常用函數和屬性的作用及常用用法,實體類是上一節的GuestInfo.cs類,資料庫也採用上一節的資料庫Database1.mdb,下面的樣本程式對對象和屬性按其功能進行了必要的分組,代碼中也有詳盡的注釋。代碼如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.Linq;using System.IO;using System.Data.SqlClient;namespace DataContext對象成員{    /// <summary>    /// 用於資料庫連接的DataContext類成員    /// </summary>    class Program    {        static void Main(string[] args)        {                        //連接字串            string constring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Visual Studio 2010\LINQ_to_SQL\LINQ_To_SQL自訂資料庫和實體類\Database1.mdf;Integrated Security=True;User Instance=True";            //1.建構函式            DataContext dc = new DataContext(constring);            //2.GetTable            Table<GuestInfoEntity> table = dc.GetTable<GuestInfoEntity>();            var query = table.AsEnumerable();            foreach(var g in query)            {                Console.WriteLine("{0} {1} {2} {3}",g.ID,g.Name,g.Age,g.Tel );            }            Console.WriteLine("-----------------");            Console.ReadKey();            string fileName = @"E:\Visual Studio 2010\LINQ_to_SQL\LINQ_To_SQL自訂資料庫和實體類\Database1.mdf";            //3.DatabaseExists、DeleteDatabase、CreateDatabase            if (dc.DatabaseExists())            {                Console.WriteLine("資料庫檔案已經存在.");                dc.DeleteDatabase();            }            dc.CreateDatabase();            if (dc.DatabaseExists())            {                Console.WriteLine("{0} 資料庫檔案建立成功.",Path.GetFileName(fileName ));            }            Console.WriteLine("-----------------");            Console.ReadKey();            //4_1.ExecuteCommand 作為LINQ補充直接用SQL指令操作資料庫            dc.ExecuteCommand("insert into tb_GuestInfo(Name,Age,Tel) values({0},{1},{2})","DebugLZQ",25,"198****1336");            foreach (var r in dc.GetTable<GuestInfoEntity>())            {                Console.WriteLine("{0} {1} {2} {3}",r.ID,r.Name,r.Age,r.Tel );            }            Console.WriteLine("-----------------");            Console.ReadKey();            //4_2.ExecuteQuery 作為LINQ補充直接用SQL指令操作資料庫            var rows= dc.ExecuteQuery<GuestInfoEntity>("select * from tb_GuestInfo");            foreach (var r in rows)            {                Console.WriteLine("{0} {1} {2} {3}", r.ID, r.Name, r.Age, r.Tel);            }            Console.WriteLine("-----------------");            Console.ReadKey();            //4_3Translate 將DbReader轉換為LINQ對象            string queryString = "select * from tb_GuestInfo";            SqlConnection connection = new SqlConnection(constring);            SqlCommand cmd = new SqlCommand(queryString, connection);            connection.Open();            var result = dc.Translate<GuestInfoEntity>(cmd.ExecuteReader());//ADO.NET轉換LINQ            foreach (var r in result)            {                Console.WriteLine("{0} {1} {2} {3}", r.ID, r.Name, r.Age, r.Tel);            }            connection.Close();            Console.WriteLine("-----------------");            Console.ReadKey();            //5.SubmitChanges 應用修改            var firstrow = (from p in dc.GetTable<GuestInfoEntity>()                                               select p).First();            firstrow.Name =firstrow.Name +"A";            dc.SubmitChanges();//應用修改            foreach (var r in dc.GetTable<GuestInfoEntity>() )            {                Console.WriteLine("{0} {1} {2} {3}", r.ID, r.Name, r.Age, r.Tel);            }            Console.WriteLine("-----------------");            Console.ReadKey();            //6.GetChangeSet方法 返回DataContext對象插入、刪除、修改過的對象            ChangeSet cs = dc.GetChangeSet();            foreach (var r in cs.Updates )            {                GuestInfoEntity t = r as GuestInfoEntity;                Console.WriteLine("{0} {1} {2} {3}", t.ID,t.Name,t.Age,t.Tel );            }            Console.WriteLine("-----------------");            Console.ReadKey();            //7.Refresh重新整理實體物件            var row1=(from g in dc.GetTable<GuestInfoEntity>() select g).First();            row1.Age = row1.Age + 5;            dc.SubmitChanges();            dc.Refresh(RefreshMode.OverwriteCurrentValues, row1);//            foreach (var r in dc.GetTable<GuestInfoEntity>())            {                Console.WriteLine("{0} {1} {2} {3}", r.ID, r.Name, r.Age, r.Tel);            }            Console.WriteLine("7-----------------");            Console.ReadKey();            //ChangeConflicts屬性 返回DataContext操作資料庫時產生的並發衝突合集            //Transaction屬性 設定或返回DataContext跟其他ADO.NET程式共用的事物對象            //ObjectTrackingEnabled屬性 開啟或關閉DataContext實體物件的狀態跟蹤                        //8.Log屬性 返回DataContext產生的SQL命令            dc.Log = Console.Out;//控制台輸出DataContext產生的SQL語句            foreach (var r in dc.GetTable<GuestInfoEntity>())            {                Console.WriteLine("{0} {1} {2} {3}", r.ID, r.Name, r.Age, r.Tel);            }            Console.WriteLine("-----------------");            Console.ReadKey();        }    }}

程式中的注釋很詳細,不再贅述。

程式的運行結果如下:

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.