新聞中心
學(xué)習(xí)LINQ時(shí),經(jīng)常會(huì)遇到LINQ DataContext類問題,這里將介紹LINQ DataContext類問題的解決方法。

創(chuàng)新互聯(lián)公司10多年成都定制網(wǎng)頁設(shè)計(jì)服務(wù);為您提供網(wǎng)站建設(shè),網(wǎng)站制作,網(wǎng)頁設(shè)計(jì)及高端網(wǎng)站定制服務(wù),成都定制網(wǎng)頁設(shè)計(jì)及推廣,對成都搬家公司等多個(gè)方面擁有多年的網(wǎng)站維護(hù)經(jīng)驗(yàn)的網(wǎng)站建設(shè)公司。
LINQ DataContext類
表示 LINQ to SQL 框架的主入口點(diǎn)。
DataContext 是輕量的,創(chuàng)建它不需要很大的開銷。典型的 LINQ to SQL 應(yīng)用程序在方法范圍內(nèi)創(chuàng)建 DataContext 實(shí)例,或?qū)⑦@些實(shí)例創(chuàng)建為生存期較短的類(這些類表示相關(guān)數(shù)據(jù)庫操作的邏輯集合)的成員。
DataContext 是用來連接到數(shù)據(jù)庫、從中檢索對象以及將更改提交回?cái)?shù)據(jù)庫的主要渠道。使用 DataContext 時(shí)就像使用 ADO.NET SqlConnection 一樣。事實(shí)上,DataContext 是用您提供的連接或連接字符串初始化的。
DataContext 的用途是將您對對象的請求轉(zhuǎn)換成要對數(shù)據(jù)庫執(zhí)行的 SQL 查詢,然后將查詢結(jié)果匯編成對象。DataContext 通過實(shí)現(xiàn)與標(biāo)準(zhǔn)查詢運(yùn)算符(如 Where 和 Select)相同的運(yùn)算符模式來實(shí)現(xiàn) 語言集成查詢 (LINQ)。
- //實(shí)體類
- [Table(Name = "Student")]
- public class Student
- {
- [Column(IsPrimaryKey = true)]
- public int ID;
- [Column]
- public string StuName;
- [Column]
- public bool Sex;
- [Column]
- public int Age;
- }
- //強(qiáng)類型DataContext
- public class TestDB : DataContext
- {
- public TestDB(string constr)
- : base(constr){
- }
- public Table Student;
- public Table Scores;
- }
- //調(diào)用
- TestDB Test = new TestDB(constr);
- var stu = from student in Test.Student
- select student;
- foreach (var st in stu)
- {
- Console.WriteLine("編號:{0},性名:{1},年齡:{2},性別:{3}",
st.ID ,st.StuName ,st.Sex ,st.Age);- }
每個(gè)數(shù)據(jù)庫表表示為一個(gè)可借助 GetTable 方法(通過使用實(shí)體類來標(biāo)識(shí)它)使用的 Table 集合。
***的做法是聲明一個(gè)強(qiáng)類型化的 DataContext,而不是依靠基本LINQ DataContext類和 GetTable 方法。強(qiáng)類型化的 DataContext 將所有 Table 集合聲明為上下文的成員,如下例中所示。
強(qiáng)類型DataContext添加
- //實(shí)體類
- [Table(Name = "Student")]
- public class Student
- {
- [Column(IsPrimaryKey = true)]
- public int ID;
- [Column]
- public string StuName;
- [Column]
- public bool Sex;
- [Column]
- public int Age;
- }
- //強(qiáng)類型DataContext
- public class TestDB : DataContext
- {
- public TestDB(string constr)
- : base(constr)
- { }
- public Table Student;
- public Table Scores;
- }
- ///添加
- TestDB Test = new TestDB(constr);
- Student student = new Student();
- student.StuName = "大張";
- student.Sex = false;
- student .Age =34;
- Test.Student.InsertOnSubmit(student);
- Test.SubmitChanges();
文章名稱:LINQDataContext類詳細(xì)介紹
網(wǎng)頁路徑:http://www.dlmjj.cn/article/cdhodhp.html


咨詢
建站咨詢
