1,在数据库中新建表,并添加字段。本例中为:student.id student.name
2,在解决方案资源管理器中添加Linq To SQL 类。 本例中为:StudentBasicClasses.dbml
3,在服务器资源管理器中打开数据库,并将表:studentinfo 拖放到Linq To SQL 类中。
现在就可以使用Linq To SQLl了:
使用时首先实例化一个Linq代理类:linq to sql 类名+datacontext 类
类似于Ajax的代理类。
studentinfo std=new studentinfo(); //声明一个实例 表名自动ORM到实体类名
context.studentinfo.insertOnSubmit(std);//添加数据
var query=from stu in context.studentinfo where stu.id="8" select stu;//选择数据
context.SubmitChanges();
/// <summary>
/// 添加数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnAdd_Click(object sender, EventArgs e)
{
StudentBasicClassesDataContext context = new StudentBasicClassesDataContext();
studentinfo std = new studentinfo();
std.id=tbId.Text;
std.name=tbName.Text;
context.studentinfo.InsertOnSubmit(std);
context.SubmitChanges();
//查看数据
System.Data.Linq.Table<studentinfo> list = context.GetTable<studentinfo>();
var query = from student in list select student;
foreach (var student in query)
{
Response.Write(student.id + " " + student.name + "<br>");
}
}
/// <summary>
/// 修改数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
StudentBasicClassesDataContext context = new StudentBasicClassesDataContext();
var query = from stu in context.studentinfo where stu.id == tbId.Text select stu;
foreach (var stu in query)
{
stu.name = tbName.Text;
}
context.SubmitChanges();
query = from student in context.studentinfo select student;
foreach (var student in query)
{
Response.Write(student.id + " " + student.name + "<br>");
}
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnDel_Click(object sender, EventArgs e)
{
StudentBasicClassesDataContext context = new StudentBasicClassesDataContext();
var query = from stu in context.studentinfo where stu.id == tbId.Text select stu;
foreach (var stu in query)
{
context.studentinfo.DeleteOnSubmit(stu);
}
context.SubmitChanges();
query = from student in context.studentinfo select student;
foreach (var student in query)
{
Response.Write(student.id + " " + student.name + "<br>");
}
}
linq to sql 的多表查询:
datacontext dc=new datacontext();
var obj = from a in dc.student
from b in dc.course
where a.sno == b.sno
select new { a.sname, b.coursename};
new {a.sname,b.coursename}; 新建一个类,返回结果。
如何实现传统SQL中的LIKE表达式:拉姆达表达式支持。
1:Customers.Where (c => c.Name.Contains ("a")) ,相当于Like '%a%'。
2:分两种写法:
1>:Customers.Where (c => c.Name.StartsWith ("a")),相当于Like 'a%'。
2>:Customers.Where (c => c.Name.EndsWith ("a")),相当于Like '%a'。
3:自己扩展一个LIKE的方法。我会在下面的文章中试试扩展LINQ TO SQL的方法。
总结:select操作对于以数据查询为主的应用程序来说特别重要,了解它的基础结构,原理后才能写出高效的应用程序。听有园友说,LINQ TO SQL可能会被抛弃,无论真与否,心中总不是个滋味,但我还是会坚持学习完LINQ TO SQL,做事总不能半途而废。