手动搭建简单的三层框架
Posted xiaoyaohan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手动搭建简单的三层框架相关的知识,希望对你有一定的参考价值。
第一、三层框架可以手动搭建,也可以用动软代码生成器来实现,本文使用手动搭建来做,首先先建立一个ASP.Net应用程序ThreeLayerWebDemo,然后在解决方案下分别建立四个类库BLL、DAL、Model、Common。
第二、在ThreeLayerWebDemo中新建一个文件夹News,在News文件夹下建立一个一般处理程序NewsList.ashx和一个NewsListTemp.html模板,并且将以上各个类库里的类名做更改,改为容易记且与类的功能属性一致得名字。
NewsList.ashx代码如下:
using Model; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; namespace ThreeLayerDemo.News { /// <summary> /// NewsList 的摘要说明 /// </summary> public class NewsList : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; BLL.NewsInfoService NewsInfoService = new BLL.NewsInfoService();//引用BLL List<NewsInfo> getNews= NewsInfoService.GetAllNews();//获得数据库里的新闻信息 StringBuilder sb = new StringBuilder(); foreach (var item in getNews) {//dId, dTId, dName, dContent, dlnTime, dEditTime, disDeleted sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td><a href=‘#‘>操作</a></td></tr>", item.dId, item.dName, item.dContent, item.dlnTime, item.dEditTime, item.disDelete); } string TempString = File.ReadAllText(context.Request.MapPath("NewsListTemp.html")); string result= TempString.Replace("@trBody", sb.ToString()); context.Response.Write(result); } public bool IsReusable { get { return false; } } } }
NewListTemp.html模板中的代码如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> </head> <body> <table border="1" width="6"> <tr> <th>dId</th><th>dName</th><th>dContent</th><th>dlnTime</th><th>dEditTime</th><th>disDeleted</th> <th>详 情</th> </tr> @trBody </table> </body> </html>
在以上一般处理程序NewsList中,当程序执行该代码时(该处的方法需要手动生成),则跳转到BLL类库下的NewsInfoService类中,并且在该类中生成GetAllNews()方法。
BLL.NewsInfoService NewsInfoService = new BLL.NewsInfoService();//引用BLL List<NewsInfo> getNews= NewsInfoService.GetAllNews();//获得数据库里的新闻信息
NewsInfoService类中的代码如下:
using Model; using DAL;
using System.Collections.Generic; namespace BLL { public class NewsInfoService { private NewsInfoDal newsInfoDal = new NewsInfoDal();//为什么要写为Private public List<NewsInfo> GetAllNews() { return newsInfoDal.GetAllNews(); } } }
Model类库下的NewsInfo类主要用于存放从数据库中采集到的数据,用属性来存储,代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public class NewsInfo { //dId, dTId, dName, dContent, dlnTime, dEditTime, disDeleted public int dId { get; set; } public string dName { get; set; } public string dContent { get; set; } public DateTime dlnTime { get; set; } public DateTime dEditTime { get; set; } public int disDelete { get; set; } } }
DAL类库中的NewsInfoDAL这个类主要是用来建立数据库连接、操作数据库使用,在该类库中还需要封装一个SQLHelper类。
NewsInfoDAL.cs 中的代码如下所示:
using Model; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class NewsInfoDal { List<NewsInfo> list = new List<NewsInfo>(); public List<NewsInfo> GetAllNews() { string sql = "select dId, dName, dContent, dlnTime, dEditTime, disDeleted from ContentInfo"; //dId, dTId, dName, dContent, dlnTime, dEditTime, disDeleted using (SqlDataReader reader=SqlHelper.ExecuteReader(sql)) { if (reader.HasRows) { while (reader.Read()) { NewsInfo dt = new NewsInfo(); dt.dId = reader.GetInt32(0); dt.dName = reader.GetString(1); dt.dContent = reader.GetString(2); dt.dlnTime = reader.GetDateTime(3); dt.dEditTime = reader.GetDateTime(4); dt.disDelete = reader.GetInt32(5); list.Add(dt); } } return list; } } } }
下面在DAL类库下封装一个SQLHelper
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public static class SqlHelper { //写三个方法:增删改,返回一个值,返回多行或多个值 //将连接数据库的字符串写在一个引用中 private static readonly string constr = ConfigurationManager.ConnectionStrings ["mysqlserver"].ConnectionString;// //写一个方法来执行增删改 public static int ExecuteNonQuery(string sql,params SqlParameter[] pms) { using (SqlConnection con=new SqlConnection (constr)) { using (SqlCommand cmd=new SqlCommand (sql,con)) { if(pms!=null) { cmd.Parameters.AddRange(pms); } con.Open(); return cmd.ExecuteNonQuery(); } } } /// <summary> /// 写一个方法执行返回一个值的 /// </summary> /// <returns></returns> public static object ExecuteScalar(string sql,params SqlParameter[] pms) { using (SqlConnection con=new SqlConnection (constr )) { using (SqlCommand cmd=new SqlCommand (sql,con)) { if(pms!=null) { cmd.Parameters.AddRange(pms);//把sql中的参数给执行命令 } con.Open(); return cmd.ExecuteScalar(); } } } /// <summary> /// 写一个方法来返回多个值 /// </summary> /// <param name="sql"></param> /// <param name="pms"></param> /// <returns></returns> public static SqlDataReader ExecuteReader(string sql,params SqlParameter[] pms) { SqlConnection con = new SqlConnection(constr); using (SqlCommand cmd = new SqlCommand(sql, con)) { if (pms != null) { cmd.Parameters.AddRange(pms); } try { con.Open(); return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);//这样返回值的时候就将连接对象关闭了 } catch { con.Close(); con.Dispose(); throw; } } } } }
数据库连接字符串写在Web.config中,(注意:在WinForm中则写在App.config中)
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <connectionStrings> <add name="Mysqlserver" connectionString="server=WIN7U-20170517Z;uid=sa;pwd=zhangyukui283166; database=2018Study"/> </connectionStrings> <system.web> <compilation debug="true" targetFramework="4.5.2"/> <httpRuntime targetFramework="4.5.2"/> <httpModules> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/> </httpModules> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE="Web" /optionInfer+"/> </compilers> </system.codedom> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="ApplicationInsightsWebTracking"/> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/> </modules> </system.webServer> </configuration>
以上是关于手动搭建简单的三层框架的主要内容,如果未能解决你的问题,请参考以下文章
.Net框架搭建之1SQL Server EF MVC简单三层框架