学习LINQ时,经常会遇到LINQ DataContext类问题,这里将介绍LINQ DataContext类问题的解决方法。
创新互联公司10多年成都定制网页设计服务;为您提供网站建设,网站制作,网页设计及高端网站定制服务,成都定制网页设计及推广,对成都搬家公司等多个方面拥有多年的网站维护经验的网站建设公司。
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();
名称栏目:LINQDataContext类详细介绍
本文网址:http://www.mswzjz.cn/qtweb/news30/288580.html
攀枝花网站建设、攀枝花网站运维推广公司-贝锐智能,是专注品牌与效果的网络营销公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 贝锐智能