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

asp.net简单3层数据库连接读取操作

2015-12-15 22:00 801 查看
简单的只有DAL,MODEL和web



UserDAL是读取数据库,和把读取的结果集,转化成泛型:

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

namespace Andu.DAL
{
public class UserDAL
{
//public List<T> GetAllListById<T>(string ConnStr, string SqlStr, int id) where T : Model.BaseModel
//{
//    SqlStr += "where ID=" + id;
//    using (SqlConnection conn = new SqlConnection(ConnStr))
//    {
//        using (SqlDataAdapter sda = new SqlDataAdapter(SqlStr, conn))
//        {
//            DataSet ds = new DataSet();
//            sda.Fill(ds);
//            return DataSetToList<T>(ds, 0);
//        }

//    }
//}
//public List<T> GetAllList<T>(string ConnStr, string SqlStr) where T:Model.BaseModel
//{
//    using (SqlConnection conn=new SqlConnection(ConnStr))
//    {
//        using (SqlDataAdapter sda=new SqlDataAdapter(SqlStr,conn))
//        {
//            DataSet ds=new DataSet();
//             sda.Fill(ds);
//             return DataSetToList<T>(ds, 0);
//        }

//    }
//}

public List<T> GetAllListById<T>(string ConnStr, string SqlStr,int id) where T : Model.BaseModel
{
SqlStr += "where ID=" + id;
using (SqlConnection conn = new SqlConnection(ConnStr))
{
SqlCommand command = new SqlCommand(SqlStr, conn);
conn.Open();
SqlDataReader read = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(read);
return DataTableToList<T>(dt);

}
}

public List<T> GetAllList<T>(string ConnStr, string SqlStr) where T : Model.BaseModel
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
SqlCommand command = new SqlCommand(SqlStr, conn);
conn.Open();
SqlDataReader read = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(read);
return DataTableToList<T>(dt);

}
}

private List<T> DataTableToList<T>(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
List<T> list = new List<T>();
T entity = default(T);
foreach (DataRow dr in dt.Rows)
{
entity = Activator.CreateInstance<T>();
PropertyInfo[] pis = entity.GetType().GetProperties();
foreach (PropertyInfo pi in pis)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite)
{
continue;
}
if (dr[pi.Name] != DBNull.Value)
{
Type t = pi.PropertyType;
if (t.FullName == "System.Guid")
{
pi.SetValue(entity, Guid.Parse(dr[pi.Name].ToString()), null);
}
else
{
pi.SetValue(entity, dr[pi.Name], null);
}

}
}
}
list.Add(entity);
}
return list;
}

public List<T> DataSetToList<T>(DataSet dataset, int p)
{
//确认参数有效
if (dataset == null || dataset.Tables.Count <= 0 || p < 0)
{
return null;
}
DataTable dt = dataset.Tables[p];
List<T> list = new List<T>();

for (int i = 0; i < dt.Rows.Count; i++)
{
//创建泛型对象
T _t = Activator.CreateInstance<T>();
//获取对象所有属性
PropertyInfo[] propertyInfo = _t.GetType().GetProperties();
//属性和名称相同时则赋值
for (int j = 0; j < dt.Columns.Count; j++)
{
foreach (PropertyInfo info in propertyInfo)
{
if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
{
if (dt.Rows[i][j] != DBNull.Value)
{
info.SetValue(_t, dt.Rows[i][j], null);
}
else
{
info.SetValue(_t, null, null);
}
break;
}
}
}
list.Add(_t);
}
return list;
}
}
}


  model层就是数据库实体类,根据数据库生成的:

basemodel:

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

namespace Andu.Model
{
public class BaseModel
{
public BaseModel() { }
public int ID { get; set; }

}
}


  UserModel:

using System;
namespace Andu.Model
{
/// <summary>User表实体类
/// 一两
/// 创建时间:2015-12-14 08:53:12
/// </summary>
[Serializable]
public class UserModel:BaseModel
{
public UserModel()
{}

private string _Name;
/// <summary>
///
/// </summary>
public string Name
{
set{ _Name=value;}
get{return _Name;}
}
private string _Account;
/// <summary>
///
/// </summary>
public string Account
{
set{ _Account=value;}
get{return _Account;}
}
private string _Password;
/// <summary>
///
/// </summary>
public string Password
{
set{ _Password=value;}
get{return _Password;}
}
private string _Email;
/// <summary>
///
/// </summary>
public string Email
{
set{ _Email=value;}
get{return _Email;}
}
private string _Mobile;
/// <summary>
///
/// </summary>
public string Mobile
{
set{ _Mobile=value;}
get{return _Mobile;}
}
private int _CompanyId;
/// <summary>
///
/// </summary>
public int CompanyId
{
set{ _CompanyId=value;}
get{return _CompanyId;}
}
private string _CompanyName;
/// <summary>
///
/// </summary>
public string CompanyName
{
set{ _CompanyName=value;}
get{return _CompanyName;}
}
private int _State;
/// <summary>用户状态  0正常 1冻结 2删除
///
/// </summary>
public int State
{
set{ _State=value;}
get{return _State;}
}
private int _UserType;
/// <summary>用户类型  1 普通用户 2管理员 4超级管理员
///
/// </summary>
public int UserType
{
set{ _UserType=value;}
get{return _UserType;}
}
private DateTime _LastLoginTime;
/// <summary>
///
/// </summary>
public DateTime LastLoginTime
{
set{ _LastLoginTime=value;}
get{return _LastLoginTime;}
}
private DateTime _CreateTime;
/// <summary>
///
/// </summary>
public DateTime CreateTime
{
set{ _CreateTime=value;}
get{return _CreateTime;}
}
private int _CreatorId;
/// <summary>
///
/// </summary>
public int CreatorId
{
set{ _CreatorId=value;}
get{return _CreatorId;}
}
private int _LastModifierId;
/// <summary>
///
/// </summary>
public int LastModifierId
{
set{ _LastModifierId=value;}
get{return _LastModifierId;}
}
private DateTime _LastModifyTime;
/// <summary>
///
/// </summary>
public DateTime LastModifyTime
{
set{ _LastModifyTime=value;}
get{return _LastModifyTime;}
}
}
}


  上门的usermodel是用自动三层生成,根据数据库自动生成的

web.config:

<?xml version="1.0" encoding="utf-8"?>

<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 -->

<configuration>
<connectionStrings>
<add name="conn" connectionString="Data Source=.;Initial Catalog=zuoye01;User ID=sa;Password=sa"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>

</configuration>


  前台页面调用:

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Web.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<table border="1">
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<tr>
<th>序号</th><th>姓名</th><th>邮箱</th><th>公司</th><th>用户类型</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("id") %></td><td><%#Eval("name") %></td><td><%#Eval("email") %></td><td><%#Eval("companyname") %></td><td><%#Eval("UserType") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</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 Andu.Model;
using Andu.DAL;
using System.Data.SqlClient;
using System.Configuration;

namespace Web
{
public partial class WebForm1 : System.Web.UI.Page
{
UserDAL userdal = new UserDAL();
protected void Page_Load(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["conn"].ToString();
string sql = "select * from [User]";

//获取全部
Repeater1.DataSource = userdal.GetAllList<UserModel>(conn, sql);
Repeater1.DataBind();

//根据ID获取
//Repeater1.DataSource = userdal.GetAllListById<UserModel>(conn, sql, 11);
//Repeater1.DataBind();

List<UserModel> usermodel = userdal.GetAllList<UserModel>(conn, sql);

//UserType由小到大排序
//usermodel.Sort((x, y) => x.UserType.CompareTo(y.UserType));

//UserType由大到小排序
//usermodel.Sort((x, y) => y.UserType.CompareTo(x.UserType));

//Repeater1.DataSource = usermodel;
//Repeater1.DataBind();

int maxu = 0;

maxu = usermodel.Max(x => x.UserType);
Label1.Text = "user表中UserType最大值是:" + maxu.ToString();

//maxu = usermodel.Min(x => x.UserType);
//Label1.Text = "user表中UserType最小值是:" + maxu.ToString();

//double pingjun = usermodel.Average(x => x.UserType);
//Label1.Text = "user表中UserType平均值是:" + pingjun.ToString("0.00");

//maxu = usermodel.Sum(x => x.UserType);
//Label1.Text = "user表中UserType和是:" + maxu.ToString();

}
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: