dbbase.cs文件
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Reflection;
using System.Collections.Generic;
using zfCMS.BLL;
namespace zfCMS.DAL
{
/// <summary>
/// 泛型操作数据库类
/// </summary>
public class DBbase<T>
{
public DBbase()
{
}
public List<T> GetModels(string cmd)
{
List<T> list = new List<T>();
T obj;
using (DataTable dt = DB.GetData(cmd))
{
foreach(DataRow dr in dt.Rows)
{
obj = (T)Activator.CreateInstance(typeof(T));
//要保证数量可多不可少
foreach (PropertyInfo fi in typeof(T).GetProperties())
{
fi.SetValue(obj, dr[fi.Name].ToString(), null);
}
list.Add(obj);
}
}
return list ;
}
public void SetModels<T>(SqlCommand cmd,CommandType ct,string[] paramsname,T post)
{
List<T> list = new List<T>();
T obj;
obj = (T)Activator.CreateInstance(typeof(T));
foreach (PropertyInfo fi in typeof(T).GetProperties())
{
foreach (string s in paramsname)
{
if (fi.Name == s)
{
cmd.Parameters.AddWithValue(fi.Name, fi.GetValue(post, null));
}
}
}
DB.ExecuteNonQuery(cmd);
}
}
}
测试用的用户实体类
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace zfCMS.BLL
{
public class TestUser
{
private string m_Name;
private int m_UserID;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
public int UserID
{
get { return m_UserID; }
set { m_UserID = value; }
}
}
}
测试用的页面后台代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace zfCMS
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
zfCMS.DAL.DBbase<zfCMS.BLL.TestUser> test = new zfCMS.DAL.DBbase<zfCMS.BLL.TestUser>();
List<zfCMS.BLL.TestUser> ltest = test.GetModels("select * from zf_User where UserID = 1");
foreach (zfCMS.BLL.TestUser tu in ltest)
{
Label1.Text = tu.Name;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
zfCMS.DAL.DBbase<zfCMS.BLL.TestUser> test = new zfCMS.DAL.DBbase<zfCMS.BLL.TestUser>();
zfCMS.BLL.TestUser t = new zfCMS.BLL.TestUser();
t.Name = "Guest1";
t.UserID = 1;
test.SetModels<zfCMS.BLL.TestUser>(new SqlCommand("zf_Test"), CommandType.StoredProcedure, new string[] { "UserID", "Name" },t);
}
}
}
主要是前两天看到了一套CMS系统,里面数据层和业务层利用泛型来写,自己回家试了两天把这东西摸了出来.主要实现读取数据绑定对象属性和根据对象属性执行存储过程更新数据库.
实现是实现了没错,但是个人对这套东西还是有怀疑.反射导致的性能消耗到底是否值得(从数据源实体化一个对象都会使用到反射),至于业务和数据层混合,以及带来的理解困难的问题,估计就要看各人自己的造化了 orz