虽然接触微软的东西时间不长,但对于orm这块,自己认为 Linq to sql 比起hibernate 要有优势,对于中小型系统,它会更活跃。不要去管微软要不要放弃 Linq to sql ,它现在能满足我的需求,而且好用,这就足够了。微软是不可能放弃对它的支持的。
出处:http://www.cnblogs.com/greatverve/archive/2010/05/13/1734236.html
尊敬知识,尊敬作者是种美德
1.接上篇http://www.cnblogs.com/greatverve/archive/2010/05/12/1733513.html
在Northwind下新建表t_User
ID, int,主键,自增。
UserName, varchar(50)
Pwd, varchar(50)
2.从服务器资源管理器中把t_User拖到Northwind.dbml中。
即生成orm映射。
3.增删改查的代码参考下面的Linq3();
代码
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Data.Common;
using
System.Collections.Generic;
namespace
FirstLinq
{
public
partial
class
_Default : System.Web.UI.Page
{
NorthwindDataContext ctx
=
new
NorthwindDataContext(
"
Data Source=ZHANGSHUQIANG;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sa
"
);
protected
void
Page_Load(
object
sender, EventArgs e)
{
Linq1();
Linq2();
Linq3();
}
///
///
增删改查
///
private
void
Linq3()
{
//
增
t_User user
=
new
t_User();
user.UserName
=
"
大气象
"
;
user.Pwd
=
"
123456
"
;
ctx.t_User.InsertOnSubmit(user);
//
以前的方法是Add();
ctx.SubmitChanges();
//
改
//
参考这样的语法string s = (from a in ctx.Customers select a).Single(a => a.ID == 2);
t_User userUpdate
=
ctx.t_User.SingleOrDefault(t_User
=>
t_User.ID
==
2
);
//
Single与SingleOrDefault没区别
userUpdate.UserName
=
"
大气象1
"
;
ctx.SubmitChanges();
//
删
t_User userDelete
=
(from userinfo
in
ctx.t_User
where
userinfo.ID
==
1
select userinfo).FirstOrDefault();
if
(userDelete
!=
null
)
{
ctx.t_User.DeleteOnSubmit(userDelete);
ctx.SubmitChanges();
}
}
///
///
熟悉Linq to sql语法
///
private
void
Linq2()
{
Customers customer
=
new
Customers();
//
执行普通的sql语句,查询CustomerID="ANATR"的记录
IEnumerable
<</span>Customers> customers = ctx.ExecuteQuery<</span>Customers>("select * from Customers where CustomerID='ANATR'");
customer = customers.First();
Response.Write(customer.CustomerID);
//使用Linq查询单条记录
var cus = from c in ctx.Customers where c.CustomerID.Equals("ANATR") select c;
customer = cus.First();
Response.Write(customer.CompanyName);
//查询结果集,语法:from 临时表名 in 表集合 orderby 临时表名.字段名 升级序 select 临时表名
gdvCustomers.DataSource = from cust in ctx.Customers where cust.CustomerID != "ANATR" orderby cust.CompanyName descending select cust;
gdvCustomers.DataBind();
}
///
/// 熟悉一下linq语法,变量的定义类似js,无须声明类型。
///
private void Linq1()
{
var age = 29;
var username = "greatverve";
var userlist = new[] { "a", "b", "c" };
foreach (var user in userlist)
{
Response.Write(user);
}
}
}
}
参考:
http://www.cnblogs.com/webabcd/archive/2007/10/18/928353.html
http://www.cnblogs.com/lovecherry/archive/2007/08/16/858009.html