支持多类型数据库的c#数据库模型示例
2016-05-13 11:13
381 查看
DataAccess.cs
DbHelper.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DynamicFramework
{
public sealed class DbHelper
{
public static List<T> ToList<T>(System.Data.IDataReader reader)
{
List<T> list = new List<T>();
Csla.Data.SafeDataReader sr = new Csla.Data.SafeDataReader(reader);
while (sr.Read())
{
T t = Activator.CreateInstance<T>();
Type entityType = t.GetType();
for (int i = 0; i < sr.FieldCount; i++)
{
string pName = reader.GetName(i);
System.Reflection.PropertyInfo p = entityType.GetProperty(pName);
if (p != null)
{
p.SetValue(t, GetValue(p,sr,i), null);
}
}
list.Add(t);
}
return list;
}
private static object GetValue(System.Reflection.PropertyInfo p,Csla.Data.SafeDataReader sr,int index)
{
if (p.PropertyType == typeof(string))
{
return sr.GetString(index);
}
else if (p.PropertyType == typeof(int))
{
return sr.GetInt32(index);
}
else if (p.PropertyType == typeof(decimal))
{
return sr.GetDecimal(index);
}
else if (p.PropertyType == typeof(DateTime))
{
return sr.GetDateTime(index);
}
else if (p.PropertyType == typeof(bool))
{
return sr.GetBoolean(index);
}
else if (p.PropertyType == typeof(double))
{
return sr.GetDouble(index);
}
else
{
return sr.GetValue(index);
}
}
public static T ToEntity<T>(System.Data.IDataReader reader)
{
Csla.Data.SafeDataReader sr = new Csla.Data.SafeDataReader(reader);
while (sr.Read())
{
T t = Activator.CreateInstance<T>();
Type entityType = t.GetType();
for (int i = 0; i < sr.FieldCount; i++)
{
string pName = reader.GetName(i);
System.Reflection.PropertyInfo p = entityType.GetProperty(pName);
if (p != null)
{
p.SetValue(t, GetValue(p, sr, i), null);
}
}
return t;
}
return default(T);
}
public static List<T> TableToList<T>(System.Data.DataTable dt)
{
return ToList<T>(dt.CreateDataReader());
}
public static System.Data.DataTable ListToTable<T>(IList<T> list)
{
if (list == null) return null;
System.Data.DataTable dt = new System.Data.DataTable(typeof(T).Name);
System.Reflection.PropertyInfo[] props = typeof(T).GetProperties();
if (props.Length >= 0)
{
for (int column = 0; column < props.Length; column++)
{
dt.Columns.Add(props[column].Name, props[column].PropertyType);
}
}
foreach (T item in list)
{
System.Data.DataRow dr = dt.NewRow();
foreach (System.Data.DataColumn column in dt.Columns)
{
dr[column] = item.GetType().GetProperty(column.ColumnName).GetValue(item, null);
}
dt.Rows.Add(dr);
}
//dt.AcceptChanges();
return dt;
}
public static System.Data.DataTable ToTable(System.Data.IDataReader reader)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(reader);
return dt;
}
public static void SaveEntity<T>(T obj)
{
string tb = obj.GetType().Name;
string SQL = "insert into {0}({1})values({2})";
string fles = "";
string sparam = "";
Dictionary<string, object> dicParams = new Dictionary<string, object>();
foreach (System.Reflection.PropertyInfo var in obj.GetType().GetProperties())
{
fles += var.Name + ",";
sparam += "@" + var.Name + ",";
dicParams.Add("@" + var.Name,var.GetValue(obj, null));
}
SQL = string.Format(SQL, tb, fles.Remove(fles.Length - 1), sparam.Remove(sparam.Length - 1));
DataAccess.ServerDb.ExecuteScalar(SQL, dicParams);
}
public static void SaveLocalEntity<T>(T obj)
{
string tb = obj.GetType().Name;
string SQL = "insert into {0}({1})values({2})";
string fles = "";
string sparam = "";
Dictionary<string, object> dicParams = new Dictionary<string, object>();
foreach (System.Reflection.PropertyInfo var in obj.GetType().GetProperties())
{
fles += var.Name + ",";
sparam += "@" + var.Name + ",";
dicParams.Add("@" + var.Name, var.GetValue(obj, null));
}
SQL = string.Format(SQL, tb, fles.Remove(fles.Length - 1), sparam.Remove(sparam.Length - 1));
DataAccess.LocalDb.ExecuteScalar(SQL, dicParams);
}
}
#region DataAsss == OleDb - SqlClient - SQLite
public class OleAccess : DataAccess
{
public OleAccess()
{
connection = new System.Data.OleDb.OleDbConnection();
}
public OleAccess(string connectionString)
{
connection = new System.Data.OleDb.OleDbConnection(connectionString);
cnnstr = connectionString;
}
internal override System.Data.Common.DbDataAdapter CreateAdapter()
{
return new System.Data.OleDb.OleDbDataAdapter();
}
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
{
return new System.Data.OleDb.OleDbCommandBuilder();
}
}
public class SqlClientAccess : DataAccess
{
public SqlClientAccess()
{
connection = new System.Data.SqlClient.SqlConnection();
}
public SqlClientAccess(string connectionString)
{
connection = new System.Data.SqlClient.SqlConnection(connectionString);
cnnstr = connectionString;
}
internal override System.Data.Common.DbDataAdapter CreateAdapter()
{
return new System.Data.SqlClient.SqlDataAdapter();
}
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
{
return new System.Data.SqlClient.SqlCommandBuilder();
}
}
public class SQLiteAccess : DataAccess
{
public SQLiteAccess()
{
connection = new System.Data.SQLite.SQLiteConnection();
}
public SQLiteAccess(string connectionString)
{
connection = new System.Data.SQLite.SQLiteConnection(connectionString);
cnnstr = connectionString;
}
internal override System.Data.Common.DbDataAdapter CreateAdapter()
{
return new System.Data.SQLite.SQLiteDataAdapter();
}
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
{
return new System.Data.SQLite.SQLiteCommandBuilder();
}
}
#endregion
}
using System; using System.Collections.Generic; using System.Text; namespace DynamicFramework { public abstract class DataAccess : MarshalByRefObject { protected System.Data.Common.DbConnection connection; protected string cnnstr = ""; protected DataAccess() { } public static string ConnPath = System.Windows.Forms.Application.StartupPath + "\\LocalDB.mdb"; public static DataAccess LocalDb { get { return new OleAccess("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ConnPath); //return new SqlClientAccess("Server=localhost;Trusted_Connection=true;Database=RestaurantDB"); } } public static DataAccess ServerDb { get { //return new OleAccess("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ConnPath); //if (Configs.LocalConfig.Instanct.IsLocalServer) //{ //} //Trusted_Connection=true; //return new SqlClientAccess("Server=.;Database=RestaurantDB,uid = sa,pwd ="); return new SqlClientAccess("Data Source=.;Initial Catalog=RestaurantDB;Persist Security Info=True;User ID=sa"); } } private System.Data.Common.DbCommand GetCommand(string sql, Dictionary<string, object> parameters) { System.Data.Common.DbCommand cmd = connection.CreateCommand(); cmd.CommandText = sql; if (parameters != null) { foreach (KeyValuePair<string, object> item in parameters) { System.Data.Common.DbParameter parameter = cmd.CreateParameter(); parameter.ParameterName = item.Key; parameter.Value = item.Value; cmd.Parameters.Add(parameter); } } return cmd; } #region DataAccess Command public int ExcuteCommand(string sql,Dictionary<string,object> parameters) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); return GetCommand(sql, parameters).ExecuteNonQuery(); } } public object ExecuteScalar(string sql, Dictionary<string, object> parameters) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); return GetCommand(sql, parameters).ExecuteScalar(); } } public object ExecuteReader(string sql, Dictionary<string, object> parameters) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); return GetCommand(sql, parameters).ExecuteReader(); } } public System.Data.DataTable ExecuteDataTable(string sql) { return ExecuteDataTable(sql, null); } public System.Data.DataTable ExecuteDataTable(string sql, Dictionary<string, object> parameters) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); return DbHelper.ToTable(GetCommand(sql, parameters).ExecuteReader()); } } public List<T> ExcuteList<T>(string sql, Dictionary<string, object> parameters) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); return DbHelper.ToList<T>(GetCommand(sql, parameters).ExecuteReader()); } } public T GetEntity<T>(string sql, Dictionary<string, object> parameters) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); return DbHelper.ToEntity<T>(GetCommand(sql, parameters).ExecuteReader()); } } public List<T> ExcuteList<T>() { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); return DbHelper.ToList<T>(GetCommand(string.Format("select * from {0}", typeof(T).Name), null).ExecuteReader()); } } public System.Data.DataTable FillDataTable(string sql) { return FillDataTable(sql, null); } public System.Data.DataTable FillDataTable(string sql, Dictionary<string, object> parameters) { System.Data.DataTable dt = new System.Data.DataTable(); Fill(dt, GetCommand(sql, parameters)); return dt; } public int Fill(System.Data.DataTable dt, System.Data.Common.DbCommand cmd) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); System.Data.Common.DbDataAdapter adapter = CreateAdapter(); adapter.SelectCommand = cmd; return adapter.Fill(dt); } } public int SaveDataTable(System.Data.DataTable dt) { return SaveDataTable(dt, dt.TableName); } public int SaveDataTable(System.Data.DataTable dt, string tableName) { return SaveTable(dt, "select * from " + tableName + " where 1 = 2"); } public int SaveTable(System.Data.DataTable dt, string sql) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); System.Data.Common.DbDataAdapter adapter = CreateAdapter(); adapter.SelectCommand = GetCommand(sql, null); System.Data.Common.DbCommandBuilder cmdBuild = CreateCommandBuilder(); cmdBuild.DataAdapter = adapter; cmdBuild.QuotePrefix = "["; cmdBuild.QuoteSuffix = "]"; return adapter.Update(dt); } } public int SaveDataSet(System.Data.DataSet ds) { using (connection) { connection.ConnectionString = cnnstr; connection.Open(); int updates = 0; foreach (System.Data.DataTable item in ds.Tables) { updates += SaveDataTable(item); } return updates; } } #endregion internal virtual System.Data.Common.DbDataAdapter CreateAdapter() { throw new System.ApplicationException("DbDataAdapter Can Not Created!"); } public virtual System.Data.Common.DbCommandBuilder CreateCommandBuilder() { throw new System.ApplicationException("DbCommandBuilder Can Not Created!"); } } }
DbHelper.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace DynamicFramework
{
public sealed class DbHelper
{
public static List<T> ToList<T>(System.Data.IDataReader reader)
{
List<T> list = new List<T>();
Csla.Data.SafeDataReader sr = new Csla.Data.SafeDataReader(reader);
while (sr.Read())
{
T t = Activator.CreateInstance<T>();
Type entityType = t.GetType();
for (int i = 0; i < sr.FieldCount; i++)
{
string pName = reader.GetName(i);
System.Reflection.PropertyInfo p = entityType.GetProperty(pName);
if (p != null)
{
p.SetValue(t, GetValue(p,sr,i), null);
}
}
list.Add(t);
}
return list;
}
private static object GetValue(System.Reflection.PropertyInfo p,Csla.Data.SafeDataReader sr,int index)
{
if (p.PropertyType == typeof(string))
{
return sr.GetString(index);
}
else if (p.PropertyType == typeof(int))
{
return sr.GetInt32(index);
}
else if (p.PropertyType == typeof(decimal))
{
return sr.GetDecimal(index);
}
else if (p.PropertyType == typeof(DateTime))
{
return sr.GetDateTime(index);
}
else if (p.PropertyType == typeof(bool))
{
return sr.GetBoolean(index);
}
else if (p.PropertyType == typeof(double))
{
return sr.GetDouble(index);
}
else
{
return sr.GetValue(index);
}
}
public static T ToEntity<T>(System.Data.IDataReader reader)
{
Csla.Data.SafeDataReader sr = new Csla.Data.SafeDataReader(reader);
while (sr.Read())
{
T t = Activator.CreateInstance<T>();
Type entityType = t.GetType();
for (int i = 0; i < sr.FieldCount; i++)
{
string pName = reader.GetName(i);
System.Reflection.PropertyInfo p = entityType.GetProperty(pName);
if (p != null)
{
p.SetValue(t, GetValue(p, sr, i), null);
}
}
return t;
}
return default(T);
}
public static List<T> TableToList<T>(System.Data.DataTable dt)
{
return ToList<T>(dt.CreateDataReader());
}
public static System.Data.DataTable ListToTable<T>(IList<T> list)
{
if (list == null) return null;
System.Data.DataTable dt = new System.Data.DataTable(typeof(T).Name);
System.Reflection.PropertyInfo[] props = typeof(T).GetProperties();
if (props.Length >= 0)
{
for (int column = 0; column < props.Length; column++)
{
dt.Columns.Add(props[column].Name, props[column].PropertyType);
}
}
foreach (T item in list)
{
System.Data.DataRow dr = dt.NewRow();
foreach (System.Data.DataColumn column in dt.Columns)
{
dr[column] = item.GetType().GetProperty(column.ColumnName).GetValue(item, null);
}
dt.Rows.Add(dr);
}
//dt.AcceptChanges();
return dt;
}
public static System.Data.DataTable ToTable(System.Data.IDataReader reader)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(reader);
return dt;
}
public static void SaveEntity<T>(T obj)
{
string tb = obj.GetType().Name;
string SQL = "insert into {0}({1})values({2})";
string fles = "";
string sparam = "";
Dictionary<string, object> dicParams = new Dictionary<string, object>();
foreach (System.Reflection.PropertyInfo var in obj.GetType().GetProperties())
{
fles += var.Name + ",";
sparam += "@" + var.Name + ",";
dicParams.Add("@" + var.Name,var.GetValue(obj, null));
}
SQL = string.Format(SQL, tb, fles.Remove(fles.Length - 1), sparam.Remove(sparam.Length - 1));
DataAccess.ServerDb.ExecuteScalar(SQL, dicParams);
}
public static void SaveLocalEntity<T>(T obj)
{
string tb = obj.GetType().Name;
string SQL = "insert into {0}({1})values({2})";
string fles = "";
string sparam = "";
Dictionary<string, object> dicParams = new Dictionary<string, object>();
foreach (System.Reflection.PropertyInfo var in obj.GetType().GetProperties())
{
fles += var.Name + ",";
sparam += "@" + var.Name + ",";
dicParams.Add("@" + var.Name, var.GetValue(obj, null));
}
SQL = string.Format(SQL, tb, fles.Remove(fles.Length - 1), sparam.Remove(sparam.Length - 1));
DataAccess.LocalDb.ExecuteScalar(SQL, dicParams);
}
}
#region DataAsss == OleDb - SqlClient - SQLite
public class OleAccess : DataAccess
{
public OleAccess()
{
connection = new System.Data.OleDb.OleDbConnection();
}
public OleAccess(string connectionString)
{
connection = new System.Data.OleDb.OleDbConnection(connectionString);
cnnstr = connectionString;
}
internal override System.Data.Common.DbDataAdapter CreateAdapter()
{
return new System.Data.OleDb.OleDbDataAdapter();
}
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
{
return new System.Data.OleDb.OleDbCommandBuilder();
}
}
public class SqlClientAccess : DataAccess
{
public SqlClientAccess()
{
connection = new System.Data.SqlClient.SqlConnection();
}
public SqlClientAccess(string connectionString)
{
connection = new System.Data.SqlClient.SqlConnection(connectionString);
cnnstr = connectionString;
}
internal override System.Data.Common.DbDataAdapter CreateAdapter()
{
return new System.Data.SqlClient.SqlDataAdapter();
}
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
{
return new System.Data.SqlClient.SqlCommandBuilder();
}
}
public class SQLiteAccess : DataAccess
{
public SQLiteAccess()
{
connection = new System.Data.SQLite.SQLiteConnection();
}
public SQLiteAccess(string connectionString)
{
connection = new System.Data.SQLite.SQLiteConnection(connectionString);
cnnstr = connectionString;
}
internal override System.Data.Common.DbDataAdapter CreateAdapter()
{
return new System.Data.SQLite.SQLiteDataAdapter();
}
public override System.Data.Common.DbCommandBuilder CreateCommandBuilder()
{
return new System.Data.SQLite.SQLiteCommandBuilder();
}
}
#endregion
}
相关文章推荐
- MySQL远程连接丢失问题解决方法Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0
- debian8下配置postgresql9.5.2、pgpool3.5.2、heartbeat3.0.5的HA热备
- 数据库分库和分表
- mysql5.711 performance_schema.session_status' doesn't exist
- Sqlserver数据库分页查询
- Mysql事务,并发问题,锁机制
- 设计高效数据库的原则
- .NET通用的数据库操作类(支持多种数据库)
- MySQL数据库存储引擎比较
- 四种方式实现SQLServer 分页查询
- 一些查看mysql信息常用sql
- SQL SERVER 对数据库的一些基本操作:创建、更改、查看、删除……
- SQL server 2014 内存表特性概述
- MongoDB常用命令
- Linux中redis主从配置
- oracle问题 plsql连接不上远程数据库
- Oracle取消用户连续登录失败次数限制
- SQL SERVER 10进制转换36进制
- Oracle11-本地连接没问题,远程连接有问题解决方案
- MYSQL必知必会读书笔记 第二十三章 使用存储过程