我想将我的架构转换为N层架构。请查看以下详细信息。 ----------------------- SQL -------------------------- ------ 使用[实践] 开始
/ ******对象:表格[dbo]。[品牌]脚本日期:03/02/2019 00:56:50 ****** /
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Brand](
[Id] [int] IDENTITY(1,1) NOT NULL,
[BrandName] [varchar](20) NULL,
[ProductId] [int] NULL,
CONSTRAINT [PK_Brand] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
----------------------------------------------------------------------------------------------------
USE [Practice]
GO
/****** Object: Table [dbo].[Product] Script Date: 03/02/2019 00:57:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Product](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProductName] [varchar](20) NULL,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
--------------------------------------------------------------------------------------------------------------------
USE [Practice]
GO
/****** Object: Table [dbo].[BrandProductAssociation] Script Date: 03/02/2019 00:58:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BrandProductAssociation](
[Id] [int] IDENTITY(1,1) NOT NULL,
[BrandId] [int] NOT NULL,
[ProductId] [int] NOT NULL,
[Price] [int] NOT NULL,
[Ingrdient] [varchar](10) NULL,
[UseFor] [varchar](10) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
--------------------------------------------------------------------------------------------------------------------
USE [Practice]
GO
/****** Object: StoredProcedure [dbo].[Proc_SelecBrand] Script Date: 03/02/2019 00:58:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Proc_SelecBrand]
@ProductId int = null
as
begin
select * from Brand where (productid =@ProductId or @ProductId is null)
end
GO
----------------------------------------------------------------------------------------------------------------------
USE [Practice]
GO
/****** Object: StoredProcedure [dbo].[Proc_SelecProduct] Script Date: 03/02/2019 00:59:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create Procedure [dbo].[Proc_SelecProduct]
as
begin
select * from Product
end
GO
------------------------------------------------------------------------------------------------------------------------
USE [Practice]
GO
/****** Object: StoredProcedure [dbo].[Proc_InsertBrandProductDetails] Script Date: 03/02/2019 01:00:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create Procedure [dbo].[Proc_InsertBrandProductDetails]
@BrandId int,
@ProductId int,
@price int,
@Ingri varchar(10),
@user varchar(10)
as
begin
Insert into BrandProductAssociation ([BrandId],[ProductId],[Price],[Ingrdient],[UseFor]) values (@BrandId,@ProductId,@price,@Ingri,@user)
end
GO
------aspx----------------------------------------------------------------
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="TestApp._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table style="width: 300px" cellspacing="4" cellpadding="4">
<tr>
<td colspan="2">
<asp:Label ID="LblMessage" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
<tr style="height: 20px">
<td style="width: 100; background-color: #e5e5e5">
Product
</td>
<td style="width: 200; background-color: #f7f7f7">
<asp:DropDownList ID="ddlProduct" runat="server" Height="19px" Width="200px" OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged"
AutoPostBack="true">
</asp:DropDownList>
<span style="color: Red">*</span>
<br />
<asp:RequiredFieldValidator ID="RFDProduct" runat="server" ErrorMessage="Please Select Product"
InitialValue="--Select Product--" ControlToValidate="ddlProduct" Display="Dynamic" ForeColor="Red" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr style="height: 20px">
<td style="width: 100; background-color: #e5e5e5">
Brand
</td>
<td style="width: 200; background-color: #f7f7f7">
<asp:DropDownList ID="ddlBrand" runat="server" Height="19px" Width="200px">
</asp:DropDownList>
<span style="color: Red">*</span>
<br />
<asp:RequiredFieldValidator ID="RFDBrand" runat="server" ErrorMessage="Please Select Brand"
InitialValue="--Select Brand--" ControlToValidate="ddlBrand" Display="Dynamic" ForeColor="Red" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr style="height: 10px">
<td style="width: 100; background-color: #e5e5e5">
Price
</td>
<td style="width: 200; background-color: #f7f7f7">
<asp:TextBox ID="txtPrice" runat="server" Width="200px" Height="19px"></asp:TextBox><span style="color: Red">*</span>
<br />
<asp:RequiredFieldValidator ID="RFDtxtPrice" runat="server" ErrorMessage="Please Enter Price" Display="Dynamic"
ControlToValidate="txtPrice" ForeColor="Red" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr style="height: 10px">
<td style="width: 100; background-color: #e5e5e5">
Ingredient
</td>
<td style="width: 200; background-color: #f7f7f7">
<asp:TextBox ID="txtIngredient" runat="server" Width="200px" Height="19px"></asp:TextBox><span
style="color: Red">*</span>
<br />
<asp:RequiredFieldValidator ID="RFDIngredient" runat="server" ErrorMessage="Please Enter Ingredient"
ControlToValidate="txtIngredient" Display="Dynamic" ForeColor="Red" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr style="height: 10px">
<td style="width: 100; background-color: #e5e5e5">
Use
</td>
<td style="width: 200; background-color: #f7f7f7">
<asp:TextBox ID="txtUse" runat="server" Width="200px" Height="19px"></asp:TextBox><span style="color: Red">*</span>
<br />
<asp:RequiredFieldValidator ID="RFDUse" runat="server" ErrorMessage="Please Enter Use"
ControlToValidate="txtUse" Display="Dynamic" ForeColor="Red" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr style="height: 10px">
<td colspan="2" align="center">
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClick="BtnSubmit_Click" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
---------------------------------------------------------------------- _--------------- cs ------------------------------------------------------using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace TestApp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["UserId"] = 2;
if (Session["UserId"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
if(!IsPostBack)
{
PopulateBrand();
PopulateProduct();
}
}
}
private void PopulateProduct()
{
try
{
DataSet ds = SqlHelpper.GetDataSet(CommandType.StoredProcedure, "Proc_SelecProduct", "Product", "PracticeConnectionString", null);
if (ds != null)
{
DataTable dt = ds.Tables["Product"];
if (dt.Rows.Count > 0)
{
ddlProduct.Items.Insert(0, "--Select Product--");
foreach (DataRow dr in dt.Rows)
{
ListItem lt = new ListItem(dr["ProductName"].ToString(), dr["Id"].ToString());
ddlProduct.Items.Add(lt);
}
}
}
}
catch (Exception ex)
{
throw;
}
}
private void PopulateBrand()
{
try
{
string Product = null;
if (ddlProduct.SelectedIndex > 0)
{
Product = ddlProduct.SelectedItem.Value;
}
DataSet ds = SqlHelpper.GetDataSet(CommandType.StoredProcedure, "Proc_SelecBrand", "Product", "PracticeConnectionString",
new SqlParameter("@ProductId", Product));
if (ds != null)
{
ddlBrand.DataSource = ds;
ddlBrand.DataTextField = "BrandName";
ddlBrand.DataValueField = "Id";
ddlBrand.DataBind();
ddlBrand.Items.Insert(0, "--Select Brand--");
}
}
catch (Exception ex)
{
throw;
}
}
protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
PopulateBrand();
}
catch (Exception ex)
{
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
int count = SqlHelpper.ExecuteNonQuery(CommandType.StoredProcedure, "Proc_InsertBrandProductDetails", "PracticeConnectionString",
new SqlParameter("@BrandId",ddlBrand.SelectedItem.Value),
new SqlParameter("@price",txtPrice.Text),
new SqlParameter("@ProductId",ddlProduct.SelectedItem.Value),
new SqlParameter("@Ingri",txtIngredient.Text),
new SqlParameter("@user",txtUse.Text));
if (count > 0)
{
// Show message
//clean control
txtIngredient.Text = "";
txtPrice.Text = "";
txtUse.Text = "";
ddlBrand.SelectedIndex = 0;
ddlProduct.SelectedIndex = 0;
LblMessage.Text = "BrandProduct details inserted sucessfully.";
}
}
}
}
--------------------在app_code下创建的帮助器类---------------------- ---------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace TestApp
{
public class SqlHelpper
{
public static DataSet GetDataSet(CommandType cmdType, string cmdText, string tabName, string connString, params SqlParameter[] cmdParms)
{
string Constring = ConfigurationManager.ConnectionStrings[connString].ConnectionString;
SqlConnection conn = new SqlConnection(Constring);
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach(SqlParameter param in cmdParms)
{
cmd.Parameters.Add(param);
}
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
da.Fill(ds, tabName);
return ds;
}
catch
{
conn.Close();
throw;
}
finally
{
conn.Close();
}
}
public static int ExecuteNonQuery(CommandType cmdType, string cmdText,string connString,params SqlParameter[] cmdParms)
{
SqlConnection conn=null;
int val=0;
try
{
string Constring = ConfigurationManager.ConnectionStrings[connString].ConnectionString;
conn = new SqlConnection(Constring);
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
val = cmd.ExecuteNonQuery();
// cmd.Parameters.Clear();
int cat = val;
conn.Close();
return val;
}
catch (Exception)
{
conn.Close();
throw;
//trans.Rollback();
}
finally
{
conn.Close();
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
}
}
答案 0 :(得分:0)
问题中的代码不是真正的n层,因为您仍然必须构建SQL命令或在ASP.Net后面的代码中列出存储过程的名称。
如果要使用n层,则必须使此处显示的SqlHelper
方法为私有。然后,对于您需要运行的每个查询,使用当前的GetDataSet()
和ExecuteNonQuery()
方法来运行该代码,从而为该特定查询添加一个新方法。此外,该类应位于其自己的类库项目中,以最终位于其自己的dll文件中。
后来,随着项目的发展,您可以将各个查询方法移动到单独的类中,以创建逻辑分组并实施不同类型的安全性,并在您的SqlHelper
内部创建该方法内部而不是私人来促进这种变化。