Linq to sql 增删改查
配置文件
<connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
代码:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace LINQPart1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShowProducts();
}
protected void Select_Click(object sender, EventArgs e)
{
ShowProducts();
}
private void ShowProducts()
{
NorthwindDataContext db = new NorthwindDataContext();
var products = from p in db.Products
where p.Category.CategoryName == "Beverages"
orderby p.ProductID descending
select new { p.ProductID, p.ProductName, p.Category.CategoryName, Price = p.UnitPrice };
GridView1.DataSource = products;
GridView1.DataBind();
}
protected void Insert_Click(object sender, EventArgs e)
{
NorthwindDataContext db = new NorthwindDataContext();
Product p1 = new Product { CategoryID = 1, ProductName = "Scott's Apple Juice", UnitPrice = 4.23m };
db.Products.InsertOnSubmit(p1);
db.SubmitChanges();
ShowProducts();
}
protected void Update_Click(object sender, EventArgs e)
{
NorthwindDataContext db = new NorthwindDataContext();
Product product = db.Products.First(p => p.ProductName.StartsWith("Scott's"));
product.UnitPrice += 2.25m;
db.SubmitChanges();
ShowProducts();
}
protected void Delete_Click(object sender, EventArgs e)
{
NorthwindDataContext db = new NorthwindDataContext();
Product product = db.Products.First(p => p.ProductName.StartsWith("Scott's"));
//foreach ()
db.Products.DeleteOnSubmit(product);
db.SubmitChanges();
ShowProducts();
}
}
}
目前维护的开源产品:https://gitee.com/475660