2、打开该类,设置Name属性(例如MyLinqDB)和Connection属性
3、服务器资源管理器内添加数据库连接
4、将数据库内需要操作的表拖入LINQ to SQL 类的设计视图,并保存
5、新建数据绑定控件例如ListView1
6、后台Page_Load编写代码:
var DB = new MyLinqDB();
var query = from t in DB.T_Users select new {t.ID, t.UserName, t.Password};
ListView1.DataSource = query.Where(t => t.ID > 0).Skip(3 * 20).Take(20);//每页20,第四页
ListView1.DataBind();
使用
LINQ
检索数据
LINQ
检索提供的语法结构与
SQL
比较接近,这让我们使用起来更加容易上手。
Northwind.dbml
自动包装了一个上下文对象
NorthwindDataContext
类,
其中包
括了我们在
Northwind
数据库中要使用的所有实体类和存储过程映射方法,
同时
还提供了操作表数据的方法,
使用时我们不需要去关心它是如何连接数据库并进
行底层数据操作的。事实上,
Northwind.dbml
文件中已经包含了这些基础设施!
使用记事本打开
Northwind.dbml
,可以发现这是一个纯粹的
XML
结构化文件,
里面包含了数据库连接字符串和一些数据库实体类的映射关系,同时,
Northwind.designer.cs
文件中也做了很多基础性的工作,
感兴趣的读者可以自
行研究其中的代码,
或许对解决实际问题有所帮助。
本文在这里不对这个文件的
具体结构作详细的解释。
下面的这个例子展示了通过
LINQ
检索
Northwind
数据库中
Customers
表
City
等于
London
的数据,并在
Command
窗口中打印出来。
1.
using (NorthwindDataContext
context
=
new
NorthwindDataContext
())
使用LINQ检索数据LINQ检索提供的语法结构与SQL比较接近,这让我们使用起来更加容易上手。
Northwind.dbml自动包装了一个上下文对象NorthwindDataContext类,其中包括了我们在Northwind数据库中要使用的所有
实体类和存储过程映射方法,同时还提供了操作表数据的方法,使用时我们不需要去关心它是如何连接数据库并进行底层数
据操作的。事实上,Northwind.dbml文件中已经包含了这些基础设施!使用记事本打开Northwind.dbml,可以发现这是一个
纯粹的XML结构化文件,里面包含了数据库连接字符串和一些数据库实体类的映射关系,同时, Northwind.designer.cs文
件中也做了很多基础性的工作,感兴趣的读者可以自行研究其中的代码,或许对解决实际问题有所帮助。本文在这里不对这
个文件的具体结构作详细的解释。 下面的这个例子展示了通过LINQ检索Northwind数据库中Customers表City等于London的
数据,并在Command窗口中打印出来。 1. using (NorthwindDataContext context =new NorthwindDataContext())
{
var results = from curstomers in context.Customers
where curstomers.City =="London" orderby curstomers.CompanyName
select curstomers; foreach (var curstomers in results)
{ Console.WriteLine("Company is {0} and Contact is {1}",
curstomers.CompanyName, curstomers.ContactName); }
// Pause to see the output Console.ReadLine(); }
使用LINQ更新数据
LINQ不仅可以从数据库中检索数据,借助于NorthwindDataContext上下文对象提供的方法,
我们也可以通过LINQ非常方便地将数据更新到数据库中。 下面的例子展示了将数据Insert和Update到数据库并
从数据库中删除数据,其中使用了LINQ中的lambda表达式用于从数据源查询数据(lambda表达式是LINQ查询语句
的一种简写形式)。 using(NorthwindDataContextcontext=newNorthwindDataContext()) {
//AddanewrecordandverifyitexiststhroughCount
var customer=new Customer()
{
CompanyName="DramaCafe", CustomerID="DRACA",
ContactName="TomSmith", City="BeverlyHills", Address="123MelrosePlace",
PostalCode="90210" }; context.Customers.InsertOnSubmit(customer);
context.SubmitChanges();
Console.WriteLine("NumberofDRACArecords:{0}",context.Customers.Where(c=>c.CustomerID=="DRACA").Count());
//ModifytherecordandverifyitischangedthroughCount
customer.ContactName="JoeSmith";
context.SubmitChanges();
Console.WriteLine("NumberofJoeSmithrecords:{0}",context.Customers.Where(c=>c.ContactName=="JoeSmith").Count());
//DeletearecordandverifyitisremovedthroughCount
context.Customers.DeleteOnSubmit(customer);
context.SubmitChanges();
Console.WriteLine("NumberofDRACArecords:{0}",context.Customers.Where(c=>c.CustomerID=="DRACA").Count());
//Pausetoseetheoutput Console.ReadLine();