62,046
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Reflection.Emit;
using System.Reflection;
using System.Xml;
namespace blog.model
{
public class BaseEntity
{
public IList<T> Query<T>(int page, int pageSize, string filter, string sorter) where T : BaseEntity
{
if (page < 1 || (pageSize < 1) && pageSize != -1)
{
return null;
}
string tp = Activator.CreateInstance<T>().GetType().ToString();
string table = GetTableName(tp);
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
#region 拼接SQL语句
string sql = "";
if (pageSize != -1)
{
if (page == 1)
{
sql = "select top " + pageSize + " * from " + table + " where 1=1 ";
}
else
{
sql = "select top " + pageSize + " * from " + table + " where id not in "
+ "(select top " + (page - 1) * pageSize + " id from " + table;
//查询条件
if (!string.IsNullOrEmpty(filter))
{
sql += " where " + filter;
}
//排序条件
if (!string.IsNullOrEmpty(sorter))
{
sql += " " + sorter + " ";
}
sql += " ) ";
}
}
else
{
sql = "select * from " + table + " where 1=1 ";
}
//查询条件
if (!string.IsNullOrEmpty(filter))
{
sql += " and " + filter;
}
//排序条件
if (!string.IsNullOrEmpty(sorter))
{
sql += " " + sorter + " ";
}
#endregion
#region 读取数据
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
IList<T> list = new List<T>();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
T entity = Activator.CreateInstance<T>();
//得到实体对应表的结构
DataTable structTable = GetTableStructure(table);
//获得实体的所有属性集合
PropertyInfo[] properties = entity.GetType().GetProperties();
for (int i = 0; i < structTable.Rows.Count; i++)
{
try
{
//给属性赋值(实体属性必须严格跟数据库中字段对应)
//相当于user.id=(int)reader["id"];
properties[i].SetValue(entity, reader[structTable.Rows[i][1].ToString()], null);
}
catch
{ continue; }
}
list.Add(entity);
}
reader.Close();
return list;
}
catch (Exception ex)
{ return null; }
#endregion
}
}
}
}
BaseEntity dao = new BaseEntity();
IList<gallerys> list = dao.Query<gallerys>(1, 5, "userid=1", "");
GridView1.DataSource = list;
GridView1.DataBind();
IList<Votes> list2 = dao.Query<Votes>(1, 5, "", "");
IList<VoteRecords> list3 = dao.Query<VoteRecords>(1, 5, "", "");
GridView2.DataSource = list2;
GridView2.DataBind();
GridView3.DataSource = list3;
GridView3.DataBind();