LINQ To SQL 的案例
ylbtech- ASP.NET-LINQ(LINQToSQL): LINQ To SQL 的案例 |
LINQ To SQL 的案例。
基本的 CRUD 操作,1,Select All. 2,Column Filter. 3,Where. 4,Order by Desc|Asc. 5,Group by. 6,Jion.
1.A,Image(运行效果图)返回顶部 |
1.B,DataSource(源代码)返回顶部 |
1.B.1.1,/App_Data/sql-basic.sql
View Code
-- ============================================= -- Create database template -- ============================================= USE master GO -- Drop the database if it already exists IF EXISTS ( SELECT name FROM sys.databases WHERE name = N'TestData' ) DROP DATABASE TestData GO CREATE DATABASE TestData GO use TestData go -- ============================================= -- 类别表 -- ============================================= create table Categorys ( cateID int identity primary key, --编号『PK』 cateName varchar(100) --名称 ) go -- ============================================= -- 产品表 -- ============================================= create table Products ( productID int identity primary key, --编号『PK』 productName varchar(100), --名称 unitprice decimal(7,2), --单价 cateID int foreign key references Categorys(cateID) --类别表的编号『FK』 ) go go -- ============================================= -- 插入测试数据 -- ============================================= go --1,Add insert into Categorys(cateName) values('水果'); insert into Categorys(cateName) values('蔬菜'); insert into Categorys(cateName) values('鱼肉'); --Add insert into Products(productName,unitprice,cateID) values('西瓜',2.5,1); insert into Products(productName,unitprice,cateID) values('苹果',2.5,1); insert into Products(productName,unitprice,cateID) values('香蕉',2.5,1); insert into Products(productName,unitprice,cateID) values('大白菜',2.5,2); insert into Products(productName,unitprice,cateID) values('芹菜',2.5,2); insert into Products(productName,unitprice,cateID) values('土豆',2.5,2); insert into Products(productName,unitprice,cateID) values('鱼肉',2.5,3); print '创建测试数据完成!'
1.B.1.2,/App_Data/Select/1,Categorys.sql
View Code
use TestData go -- ============================================= -- 1,对类别表的操作 -- ============================================= go --1,Add insert into Categorys(cateName) values('水果'); insert into Categorys(cateName) values('蔬菜'); insert into Categorys(cateName) values('鱼肉'); go --Select All select cateID,cateName from Categorys;
1.B.1.3,/App_Data/Select/2,Products.sql
View Code
use TestData go -- ============================================= -- 2,对产品表的操作 -- ============================================= --Add insert into Products(productName,unitprice,cateID) values('西瓜',2.5,1); insert into Products(productName,unitprice,cateID) values('苹果',2.5,1); insert into Products(productName,unitprice,cateID) values('香蕉',2.5,1); insert into Products(productName,unitprice,cateID) values('大白菜',2.5,2); insert into Products(productName,unitprice,cateID) values('芹菜',2.5,2); insert into Products(productName,unitprice,cateID) values('土豆',2.5,2); insert into Products(productName,unitprice,cateID) values('鱼肉',2.5,3); go --Delete delete Products where productID=1; go --Update update Products set productName='西瓜',unitprice=2.3,cateID=1 where productID=1; go --Select select productID,productName,unitprice,cateID from Products;
以上是数据设计,3
1.B.2.1,/AddProduct.aspx
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DemoBasic.aspx.cs" Inherits="DemoBasic" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/AddProduct.aspx">添加商品</asp:HyperLink> <hr /> <br /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" onrowcancelingedit="GridView1_RowCancelingEdit" onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" Width="600px" onrowdatabound="GridView1_RowDataBound"> <Columns> <asp:TemplateField HeaderText="编号"> <EditItemTemplate> <asp:Label ID="Label4" runat="server" Text='<%# Bind("productID") %>'></asp:Label> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("productID") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="名称"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("productName") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("productName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="单价"> <EditItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("unitprice") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("unitprice") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:CommandField HeaderText="edit" ShowEditButton="True" /> <asp:CommandField HeaderText="delete" ShowDeleteButton="True" /> </Columns> </asp:GridView> <br /> <br /> 遗留问题:分组没有解决<br /> </div> </form> </body> </html>
1.B.2.2,/AddProduct.aspx.cs
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class DemoBasic : System.Web.UI.Page { TestDataDataContext TestData = new TestDataDataContext(); //Bind Products public void BindProducts2a() { ////all //GridView1.DataSource = TestData.Products; //GridView1.DataBind(); ////all2 //var query = from p in TestData.Products select p; //GridView1.DataSource = query; //GridView1.DataBind(); ////coloumnfilter //var query = from p in TestData.Products select p; //GridView1.DataSource = query; //GridView1.DataBind(); ////One conditions //var query = from p in TestData.Products where p.productID==2 select p; //GridView1.DataSource = query; //GridView1.DataBind(); ////Two conditions //var query = from p in TestData.Products where p.productID == 2 || p.productName == "骆崇飞3" select p; //GridView1.DataSource = query; //GridView1.DataBind(); ////Order by desc //var query = from p in TestData.Products orderby p.productID descending select p; //GridView1.DataSource = query; //GridView1.DataBind(); //group by var query = from p in TestData.Products group p by p.productName; //foreach (var pgroup in query) //{ // Console.WriteLine(pgroup.Key); // //foreach(CustomValidator //} //GridView1.DataSource = query; //GridView1.DataBind(); } /// <summary> //1,Select All /// </summary> public void BindProducts1_1() { GridView1.DataSource = TestData.Products; GridView1.DataBind(); } public void BindProducts1_2() { var query = from prod in TestData.Products select prod; GridView1.DataSource = query; GridView1.DataBind(); } /// <summary> /// 2,columnfilter /// </summary> public void BindProducts1_3() { var query = from prod in TestData.Products select new {prod.productID,prod.productName}; GridView1.DataSource = query; GridView1.DataBind(); } /// <summary> /// 3,Where /// a)&& /// b)|| /// c)!| /// d)--like /// </summary> public void BindProducts3() { var query = from prod in TestData.Products where prod.cateID == 1 select prod; GridView1.DataSource = query; GridView1.DataBind(); } /// <summary> /// 3,order desc|asc /// </summary> public void BindProducts4() { var query = from prod in TestData.Products where prod.cateID == 1 orderby prod.productID descending select prod; GridView1.DataSource = query; GridView1.DataBind(); } //5,--group by public void BindProducts5() { var query = from prod in TestData.Products where prod.cateID == 1 group prod by prod.cateID; GridView1.DataSource = query; GridView1.DataBind(); } //6,join public void BindProducts6() { var query = from prod in TestData.Products join cate in TestData.Categorys on prod.cateID equals cate.cateID select new {prod.productName,cate.cateName}; GridView1.DataSource = query; GridView1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Call BindProducts1_1(); } } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { Label productIDLabel = (Label)GridView1.Rows[e.RowIndex].FindControl("Label1"); int productID = Convert.ToInt32(productIDLabel.Text); //Delete one product var query = from prod in TestData.Products where prod.productID == productID select prod; //删除 foreach (var p in query) { TestData.Products.DeleteOnSubmit(p); } //更新数据库 TestData.SubmitChanges(); //更新数据 BindProducts1_1(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { Label productIDLabel = (Label)GridView1.Rows[e.RowIndex].FindControl("Label4"); TextBox productNameTextBox = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2"); TextBox unitpriceTextBox = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3"); int productID = Convert.ToInt32(productIDLabel.Text); decimal unitprice = Convert.ToDecimal(unitpriceTextBox.Text); //M:update product var query = from prod in TestData.Products where prod.productID == productID select prod; foreach (var p in query) { p.productName = productNameTextBox.Text; p.unitprice = unitprice; } //Refresh data TestData.SubmitChanges(); //Cancel state editor. GridView1.EditIndex = -1; //Refresh data BindProducts1_1(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //Cancel state editor. GridView1.EditIndex = -1; //Refresh data BindProducts1_1(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { //To the edit state. GridView1.EditIndex = e.NewEditIndex; //Refresh data BindProducts1_1(); } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[4].Attributes.Add("onclick", "return confirm('您是否要删除该行数据');"); } } }
1.B.2.3,/DemoBasic.aspx
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddProduct.aspx.cs" Inherits="AddProduct" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .style1 { width: 103px; } </style> </head> <body> <form id="form1" runat="server"> <div> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/DemoBasic.aspx">查看产品列表</asp:HyperLink> <br /> <hr /> 添加一条商品<br /> <table style="width:100%;"> <tr> <td class="style1"> 名称:</td> <td> <asp:TextBox ID="txtProductName" runat="server"></asp:TextBox> </td> <td> </td> </tr> <tr> <td class="style1"> 单价:</td> <td> <asp:TextBox ID="txtUnitPrice" runat="server"></asp:TextBox> </td> <td> </td> </tr> <tr> <td class="style1"> 类别:</td> <td> <asp:DropDownList ID="dropCategorys" runat="server"> </asp:DropDownList> </td> <td> </td> </tr> <tr> <td class="style1"> </td> <td> <asp:Button ID="Button1" runat="server" Text="添加" onclick="Button1_Click" /> </td> <td> </td> </tr> <tr> <td class="style1"> </td> <td> <asp:Label ID="Label5" runat="server" Text="Label"></asp:Label> </td> <td> </td> </tr> </table> </div> </form> </body> </html>
1.B.2.4,/DemoBasic.aspx.cs
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class AddProduct : System.Web.UI.Page { TestDataDataContext TestData = new TestDataDataContext(); //Bind Categorys private void BindCategorys() { dropCategorys.DataSource = TestData.Categorys; dropCategorys.DataTextField = "cateName"; dropCategorys.DataValueField = "cateID"; dropCategorys.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Call BindCategorys(); } } protected void Button1_Click(object sender, EventArgs e) { //Add Product decimal price = Convert.ToDecimal(txtUnitPrice.Text); //Create product object. Products prod = new Products() { productName = txtProductName.Text, unitprice = price }; //Add TestData.Products.InsertOnSubmit(prod); //Refresh data TestData.SubmitChanges(); Label5.Text = "Add seccess."; } }
配置文件,
1.B.3,/web.config
View Code
<?xml version="1.0"?> <!-- 注意: 除了手动编辑此文件外,您还可以使用 Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的 “网站”->“Asp.Net 配置”选项。 有关设置和注释的完整列表可以在 machine.config.comments 中找到,该文件通常位于 \Windows\Microsoft.Net\Framework\vx.x\Config 中 --> <configuration> <configSections> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/> <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> </sectionGroup> </sectionGroup> </sectionGroup> </configSections> <appSettings/> <connectionStrings> <add name="TestDataConnectionString" connectionString="Data Source=.;Initial Catalog=TestData;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <!-- 设置 compilation debug="true" 可将调试符号插入到 已编译的页面。由于这会 影响性能,因此请仅在开发过程中将此值 设置为 true。 --> <compilation debug="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies> </compilation> <!-- 通过 <authentication> 节可以配置 安全身份验证模式,ASP.NET 使用该模式来识别来访用户身份。 --> <authentication mode="Windows"/> <!-- 如果在执行请求的过程中出现未处理的错误, 则通过 <customErrors> 节 可以配置相应的处理步骤。具体而言, 开发人员通过该节可配置要显示的 html 错误页, 以代替错误堆栈跟踪。 <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> --> <pages> <controls> <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </controls> </pages> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpModules> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="WarnAsError" value="false"/> </compiler> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="OptionInfer" value="true"/> <providerOption name="WarnAsError" value="false"/> </compiler> </compilers> </system.codedom> <!-- system.webServer 节是在 Internet Information Services 7.0 下运行 ASP.NET AJAX 所必需的。对早期版本的 IIS 来说则不需要此节。 --> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="ScriptModule"/> <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <remove name="ScriptHandlerFactory"/> <remove name="ScriptHandlerFactoryAppServices"/> <remove name="ScriptResource"/> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </handlers> </system.webServer> <runtime> <assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
1.C,FreeDownload(资源下载)返回顶部 |
https://files.cnblogs.com/ylbtech/WebFrom-LINQToSQL.rar
作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |