LINQ DataContext類詳細介紹
學(xué)習(xí)LINQ時,經(jīng)常會遇到LINQ DataContext類問題,這里將介紹LINQ DataContext類問題的解決方法。
LINQ DataContext類
表示 LINQ to SQL 框架的主入口點。
DataContext 是輕量的,創(chuàng)建它不需要很大的開銷。典型的 LINQ to SQL 應(yīng)用程序在方法范圍內(nèi)創(chuàng)建 DataContext 實例,或?qū)⑦@些實例創(chuàng)建為生存期較短的類(這些類表示相關(guān)數(shù)據(jù)庫操作的邏輯集合)的成員。
DataContext 是用來連接到數(shù)據(jù)庫、從中檢索對象以及將更改提交回數(shù)據(jù)庫的主要渠道。使用 DataContext 時就像使用 ADO.NET SqlConnection 一樣。事實上,DataContext 是用您提供的連接或連接字符串初始化的。
DataContext 的用途是將您對對象的請求轉(zhuǎn)換成要對數(shù)據(jù)庫執(zhí)行的 SQL 查詢,然后將查詢結(jié)果匯編成對象。DataContext 通過實現(xiàn)與標(biāo)準查詢運算符(如 Where 和 Select)相同的運算符模式來實現(xiàn) 語言集成查詢 (LINQ)。
- //實體類
 - [Table(Name = "Student")]
 - public class Student
 - {
 - [Column(IsPrimaryKey = true)]
 - public int ID;
 - [Column]
 - public string StuName;
 - [Column]
 - public bool Sex;
 - [Column]
 - public int Age;
 - }
 - //強類型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);- }
 
每個數(shù)據(jù)庫表表示為一個可借助 GetTable 方法(通過使用實體類來標(biāo)識它)使用的 Table 集合。
***的做法是聲明一個強類型化的 DataContext,而不是依靠基本LINQ DataContext類和 GetTable 方法。強類型化的 DataContext 將所有 Table 集合聲明為上下文的成員,如下例中所示。
強類型DataContext添加
- //實體類
 - [Table(Name = "Student")]
 - public class Student
 - {
 - [Column(IsPrimaryKey = true)]
 - public int ID;
 - [Column]
 - public string StuName;
 - [Column]
 - public bool Sex;
 - [Column]
 - public int Age;
 - }
 - //強類型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();
 
【編輯推薦】















 
 
 
 
 
 
 