LINQ DataContext類詳細介紹
學習LINQ時,經常會遇到LINQ DataContext類問題,這里將介紹LINQ DataContext類問題的解決方法。
LINQ DataContext類
表示 LINQ to SQL 框架的主入口點。
DataContext 是輕量的,創建它不需要很大的開銷。典型的 LINQ to SQL 應用程序在方法范圍內創建 DataContext 實例,或將這些實例創建為生存期較短的類(這些類表示相關數據庫操作的邏輯集合)的成員。
DataContext 是用來連接到數據庫、從中檢索對象以及將更改提交回數據庫的主要渠道。使用 DataContext 時就像使用 ADO.NET SqlConnection 一樣。事實上,DataContext 是用您提供的連接或連接字符串初始化的。
DataContext 的用途是將您對對象的請求轉換成要對數據庫執行的 SQL 查詢,然后將查詢結果匯編成對象。DataContext 通過實現與標準查詢運算符(如 Where 和 Select)相同的運算符模式來實現 語言集成查詢 (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;
- }
- //調用
- 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);- }
每個數據庫表表示為一個可借助 GetTable 方法(通過使用實體類來標識它)使用的 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();
【編輯推薦】