您的位置:首页 > 编程语言 > C#

C#教程之自己动手写映射第一节[动机]

2012-07-20 22:36 288 查看
前言撒:

最近在园子里看到不少老鸟们写一些orm相关的文章。。。做为菜鸟的我有感而发,因为本人也一直在完善自己的om框架做为平时的娱乐。
所谓“授人以鱼,不如授之以渔”,当我看到老鸟们写的文章时,大部份只写了部分核心代码和使用方法并且开源。站在使用价值的角度来说,确实实用代码量少,重用性高,操作简单啦等等.....可是站在学习的角度来看,用咱们专业的词语“抽象”来描述也不为过。初学者在看代码的时候在思想的层面上很难理解。我脚得吧,学习进步的一个重要体现首先是思想上进步了,然后才能达到技术上的进步。有想法然后去实现,你说对不。

对于“C#教程之自己动手写映射”这个分类,为什么没有叫自己动手写orm,首先是基于对orm的理解:对象关系映射,在我自己写的框架中只体现了object与table的一对一映射,至于对象与对象的关系[继承、组合、聚合等],在我自己写的框架里并没有体现出来,我写这个小东西的目地就是为了解决底层重复开发的问题,如:对于简单的增,删除改查 ,分页等,我们每个项目的每个表几乎都会用到,对于这样重复的工作,我们会尽量想办法减少我们的工作量,这就是我写这个小东西的初忠。这个系列的文章的意义并不在于应用,更多描述的是一个开发的过程和一种思想的演变过程。
作为一个博客园的一员,“代码改变世界”的苦逼程序员,我希望通过该系列文章能够让和我一样的菜鸟童鞋们共同进步 ,少走弯路,把学习的曲线拉的更平,同时希望园子里们的大牛啦,大大牛啦,老鸟啦,老老鸟啦,多多给予批评指正。

注:对于解决业务上的复杂关系我还没想过往底层整,如果你觉得不完善的话可以在我的框架基础上接着写自己的东西出来,本框架在系列教程的最后开源。

正文撒:

同样是写一个添加新员工和获取新员工分页列表的程序,我们大概可能经历以下几个阶段的写法。

有图有真相:



一、初识.net,相信大家初学.net 的时候都是这样写代码的:

页面:

<!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">
---------------------添加员工---------------------<br />
员工姓名:<asp:TextBox ID="Name" runat="server"></asp:TextBox><br />
登陆密码:<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox><br />
部门:<asp:TextBox ID="Department" runat="server"></asp:TextBox><br />
职位:<asp:TextBox ID="Position" runat="server"></asp:TextBox><br />
<asp:Button ID="Submit" runat="server" Text="确定" OnClick="btnSubmit_Click" />
<asp:Button ID="Button1" runat="server" Text="取消" OnClick="Button1_Click" /><br />
<br />
<br />
---------------------员工列表---------------------<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="2" CellPadding="4"
ForeColor="#333333" GridLines="None"
OnPageIndexChanging="GridView1_PageIndexChanging" AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="编号" />
<asp:BoundField DataField="Name" HeaderText="员工姓名" />
<asp:BoundField DataField="Password" HeaderText="密码" />
<asp:BoundField DataField="Department" HeaderText="部门" />
<asp:BoundField DataField="Position" HeaderText="职位" />
</Columns>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</form>
</body>
</html>


处理程序:

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 CSharp.WebSite.Begin
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
InitPage();
}
}

public void InitPage()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=192.168.1.8;Initial Catalog=Test;User ID=sa;Password=123!@#abc";
string select = "select * from employee";
SqlDataAdapter ad = new SqlDataAdapter(select, conn);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = this.Name.Text;
string password = this.Password.Text;
string department = this.Department.Text;
string position = this.Position.Text;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=192.168.1.8;Initial Catalog=Test;User ID=sa;Password=123!@#abc";
string insert = "insert into Employee (Name,Password,Department,Position) values ('" + name + "','" + password + "','" + department + "','" + position + "')";
SqlCommand cmd = new SqlCommand(insert, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Write("<script>alert('成功')</script>");
}

protected void Button1_Click(object sender, EventArgs e)
{
this.Name.Text = "";
this.Password.Text = "";
this.Department.Text = "";
this.Position.Text = "";
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
InitPage();
}
}
}


就这样,我们用了一个很牛逼Gridview和一个很牛逼的CodeBehind,实现了所有的东西....显示、业务、数据操作......等..

二、自己封装了SQLHelper和使用了开源程序集Aspnetpager。

我们就这样写了一段时间后,发现应该做点什么,然后就自己动手写了个sql帮助类用来处理底层与数据库的常用操作,实现了几个基本的方法GetDataSet、ExecuteNonQuery等等。接触了AspnetPager控件,并针对这个控件在网上淘了分页的存储过程,再次针对我们常用的分页控件的底层进行了封装,这样我们每次写代码的时候就直接调用方法即可了。

依然上图:



那个分页就是没有加任何样式的Aspnetpager控件。

代码如下[前台]:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="CSharp.WebSite.AboutOneYear.Index" %>

<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>
<!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 id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
---------------------添加员工---------------------<br />
员工姓名:<asp:TextBox ID="Name" runat="server"></asp:TextBox><br />
登陆密码:<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox><br />
部门:<asp:TextBox ID="Department" runat="server"></asp:TextBox><br />
职位:<asp:TextBox ID="Position" runat="server"></asp:TextBox><br />
<asp:Button ID="Submit" runat="server" Text="确定" OnClick="btnSubmit_Click" />
<asp:Button ID="Button1" runat="server" Text="取消" OnClick="Button1_Click" /><br />
<br />
<br />
---------------------员工列表---------------------<br />
<asp:Repeater ID="repList" runat="server">
<ItemTemplate>
<div style="width:300px;">
<span>
<%#Eval("ID")%></span>
<span>
<%#Eval("Name")%></span>
<span>
<%#Eval("Password")%></span>
<span>
<%#Eval("Department")%></span>
<span>
<%#Eval("Position")%></span>
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<webdiyer:AspNetPager ID="Pager" CssClass="Pager" runat="server" AlwaysShow="True"
FirstPageText="首页" InvalidPageIndexErrorMessage="请输入数字页码!" LastPageText="末页"
NextPageText="下一页" PageIndexOutOfRangeErrorMessage="页码超出范围!" PrevPageText="上一页"
ShowNavigationToolTip="True" SubmitButtonText="确定" CenterCurrentPageButton="True"
PageIndexBoxType="TextBox" PageSize="2" ShowPageIndexBox="never" TextAfterPageIndexBox=" 页 "
TextBeforePageIndexBox="转到 " HorizontalAlign="NotSet" CurrentPageButtonClass=""
OnPageChanged="Pager_PageChanged">
</webdiyer:AspNetPager>
</form>
</body>
</html>


处理程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace CSharp.WebSite.AboutOneYear
{
public partial class Index : System.Web.UI.Page
{
public readonly static string conn = "Data Source=192.168.1.8;Initial Catalog=Test;User ID=sa;Password=123!@#abc";

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetList();
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = this.Name.Text;
string password = this.Password.Text;
string department = this.Department.Text;
string position = this.Position.Text;

string insert = "insert into Employee (Name,Password,Department,Position) values ('" + name + "','" + password + "','" + department + "','" + position + "')";
SqlHelper.ExecuteNonQuery(conn, CommandType.Text, insert);
Response.Write("<script>alert('成功')</script>");
}

/// <summary>
/// 获取列表
/// </summary>
protected void GetList()
{
int TotalCount;
repList.DataSource = SqlCommon.GetList(conn, "ID", this.Pager.PageSize, Pager.PageSize * (Pager.CurrentPageIndex - 1), "Employee", "1=1", out TotalCount);
repList.DataBind();
Pager.RecordCount = TotalCount;
}

protected void Button1_Click(object sender, EventArgs e)
{
this.Name.Text = "";
this.Password.Text = "";
this.Department.Text = "";
this.Position.Text = "";
}

#region 分页
/// <summary>
/// 分页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Pager_PageChanged(object sender, EventArgs e)
{
GetList();
}
#endregion

}
}


三、又经过了一个段时间的学习后,我们接触了大名顶顶的“三层架构”,知道了以前的写法有些弊端,知道怎么把表

示层(UI)-->业务逻辑层(BLL)-->数据操作层(DAL)分离开,这时我们可能还在用SQLHelper和AspnetPager控件..
代码如下[CodeBehind]:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CSharp.WebSite.AboutTwoYear
{
public partial class Index : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetList();
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
Model.Employee employee = new Model.Employee();
employee.Name = this.Name.Text;
employee.Password = this.Password.Text;
employee.Department = this.Department.Text;
employee.Position = this.Position.Text;
if (BLL.Employee.Insert(employee))
Response.Write("<script>alert('成功')</script>");
else
Response.Write("<script>alert('失败')</script>");

}

/// <summary>
/// 获取列表
/// </summary>
protected void GetList()
{
int TotalCount;
repList.DataSource = BLL.Employee.GetList(Pager.PageSize, Pager.CurrentPageIndex, out TotalCount);
repList.DataBind();
Pager.RecordCount = TotalCount;
}

protected void Button1_Click(object sender, EventArgs e)
{
this.Name.Text = "";
this.Password.Text = "";
this.Department.Text = "";
this.Position.Text = "";
}

#region 分页
/// <summary>
/// 分页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Pager_PageChanged(object sender, EventArgs e)
{
GetList();
}
#endregion

}
}


BLL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
public class Employee
{
public static bool Insert(Model.Employee employee)
{
return DAL.Employee.Insert(employee);
}

public static List<Model.Employee> GetList(int PageSize, int CurrentPageIndex, out int TotalCount)
{
return DAL.Employee.GetList(PageSize, CurrentPageIndex, out TotalCount);
}
}
}


DAL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DAL
{
public class Employee
{
public readonly static string conn = "Data Source=192.168.1.8;Initial Catalog=Test;Employee ID=sa;Password=123!@#abc";

public static bool Insert(Model.Employee employee)
{
string insert = "insert into Employee (Name,Password,Department,Position) values ('" + employee.Name + "','" + employee.Password + "','" + employee.Department + "','" + employee.Position + "')";
if (Convert.ToInt32(SqlHelper.ExecuteNonQuery(conn, CommandType.Text, insert)) > 0)
return true;
else
return false;
}

public static List<Model.Employee> GetList(int PageSize, int CurrentPageIndex, out int TotalCount)
{
List<Model.Employee> listEmployee = new List<Model.Employee>();
DataSet ds = SqlCommon.GetList(conn, "ID", PageSize, PageSize * (CurrentPageIndex - 1), "Employee", "1=1", out TotalCount);
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
Model.Employee employee = new Model.Employee();
employee.ID = Convert.ToInt32(dr["ID"]);
employee.Name = dr["Name"].ToString();
employee.Password = dr["Password"].ToString();
employee.Department = dr["Department"].ToString();
employee.Position = dr["Position"].ToString();
listEmployee.Add(employee);
}
}
return listEmployee;
}

}
}


四、又经过一段时间的学习,我们触到了PetShop教学实例,接触了linq、nhibernate、企业库,泥马,这就是一条不归路啊,搞设计模式,基于框架开发,研究框架的思想等....
代码略...

五、在经过了一痛彻心菲的学习以后,我们总结经验,准备动手写一些自己的东西,把一些基本的功能封装起来,对外提供一致的接口去调用...好吧,我们“搞个对象”关系映射,解决一些一直重复写的 insert select update delete 等问题....
代码如下:

DAL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HZYT.DBUtility;

namespace DAL
{
public class EmployeeORM
{
public static bool Add(Model.Employee employee)
{
return ORM.Add(employee, Constant.ASSEMBLYPATH, Constant.CONNSTRING);
}

public static List<Model.Employee> GetList(int PageSize, int CurrentCount, out int TotalCount)
{
List<Model.Employee> returnList = new List<Model.Employee>();
List<object> employeeList = ORM.GetList(new Model.Employee(), PageSize, CurrentCount, out  TotalCount, Constant.ASSEMBLYPATH, Constant.CONNSTRING);
foreach (object tempobject in employeeList)
{
returnList.Add((Model.Employee)tempobject);
}
return returnList;
}
}
}


在上面的例子中,我们没有看到一个sql语句【当然sql肯定会用到的】,我们只要把Employee:new 一个,然后交给orm类就可以了,下面所有的工作都由:orm来处理啦。

以下是orm的几个常用的接口:

public class ORM
{
public ORM();

public static bool Add(object classObject, string AssemblyName, string ConnString);
public static bool Add(object classObject, out int intMaxID, string AssemblyName, string ConnString);
public static object Get(object classObject, string AssemblyName, string ConnString);
public static object Get(object classObject, string strWHERE, string AssemblyName, string ConnString);
public static List<object> GetList(object classObject, string AssemblyName, string ConnString);
public static List<object> GetList(object classObject, string strWHERE, string AssemblyName, string ConnString);
public static List<object> GetList(object classObject, int intPageSize, int intCurrentCount, out int intTotalCount, string AssemblyName, string ConnString);
public static List<object> GetList(object classObject, int intPageSize, int intCurrentCount, string strWhere, out int intTotalCount, string AssemblyName, string ConnString);
public static bool Remove(List<object> listClassObject, string AssemblyName, string ConnString);
public static bool Remove(object classObject, string AssemblyName, string ConnString);
public static bool Save(object classObject, string AssemblyName, string ConnString);
}


通过上面的例子大家看到了吧,对象关系映射其实还是挺好用的,这也是为什么园子里的很多程序员都自己写着用的原因。
今天先到这里吧,关于怎么开发这样一个微型框架我们后面的教程接着捣鼓...

06 C#映射教程源码下载

转载请注明出处:http://www.cnblogs.com/iamlilinfeng
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: