首页 > 代码库 > Linq to sql 增删改查(转帖)
Linq to sql 增删改查(转帖)
代码
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->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();
}
/// <summary>
/// 增删改查
/// </summary>
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();
}
}
/// <summary>
/// 熟悉Linq to sql语法
/// </summary>
private void Linq2()
{
Customers customer = new Customers();
//执行普通的sql语句,查询CustomerID="ANATR"的记录
IEnumerable<Customers> customers = ctx.ExecuteQuery<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();
}
/// <summary>
/// 熟悉一下linq语法,变量的定义类似js,无须声明类型。
/// </summary>
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/greatverve/archive/2010/05/13/1734236.html
Linq to sql 增删改查(转帖)