using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.Model
{
publicclass BaseModel
{
publicint Id { get; set; }
}
}
2、定义Student类继承自BaseModel基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.Model
{
publicclass Student : BaseModel
{
publicstring Name { get; set; }
publicint Age { get; set; }
publicint Sex { get; set; }
publicstring Email { get; set; }
}
}
3、定义数据库访问方法接口
using FunApplication.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.IDAL
{
publicinterface IBaseDAL
{
T Query(int id) where T : BaseModel;
List QueryAll() where T : BaseModel;
int Insert(T t) where T : BaseModel;
int Update(T t) where T : BaseModel;
int Delete(int id) where T : BaseModel;
}
}
4、定义属性帮助类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.AttributeExtend
{
publicstaticclass AttributeHelper
{
publicstaticstring GetColumnName(this PropertyInfo prop)
{
if (prop.IsDefined(typeof(ColumnAttribute), true))
{
ColumnAttribute attribute = (ColumnAttribute)prop.GetCustomAttribute(typeof(ColumnAttribute), true);
return attribute.GetColumnName();
}
else
{
return prop.Name;
}
}
}
}
5、定义ColumnAttribute类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.AttributeExtend
{
[AttributeUsage(AttributeTargets.Property)]
publicclass ColumnAttribute : Attribute
{
public ColumnAttribute(string name)
{
this._Name = name;
}
privatestring _Name = null;
publicstring GetColumnName()
{
returnthis._Name;
}
}
}
6、定义数据库方法接口实现类
using FunApplication.IDAL;
using FunApplication.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using FunApplication.AttributeExtend;
namespace FunApplication.DAL
{
publicclass BaseDAL : IBaseDAL
{
// 数据库链接字符串privatestaticstring strConn = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
publicint Delete(int id) where T : BaseModel
{
int result = 0;
using (SqlConnection conn = new SqlConnection(strConn))
{
string strSQL = "delete from Student where Id=@Id";
SqlParameter para = new SqlParameter("Id", id);
SqlCommand command = new SqlCommand(strSQL, conn);
command.Parameters.Add(para);
conn.Open();
result = command.ExecuteNonQuery();
}
return result;
}
publicint Insert(T t) where T : BaseModel
{
int result = 0;
using (SqlConnection conn = new SqlConnection(strConn))
{
Type type = typeof(T);
var propArray = type.GetProperties().Where(p => p.Name != "Id");
string strSQL = "insert into Student Values (@Name,@Age,@Sex,@Email) ";
SqlCommand command = new SqlCommand(strSQL, conn);
var parameters = propArray.Select(p => new SqlParameter($"@{p.GetColumnName()}", p.GetValue(t) ?? DBNull.Value)).ToArray();
command.Parameters.AddRange(parameters);
conn.Open();
result = command.ExecuteNonQuery();
}
return result;
}
public T Query(int id) where T : BaseModel
{
Type type = typeof(T);
string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]"));
string sql = $"SELECT {columnString} FROM [{type.Name}] WHERE Id={id}";
T t = null;// (T)Activator.CreateInstance(type);using (SqlConnection conn = new SqlConnection(strConn))
{
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
List list = this.ReaderToList(reader);
t = list.FirstOrDefault();
}
return t;
}
public List QueryAll() where T : BaseModel
{
Type type = typeof(T);
string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]"));
string sql = $"SELECT {columnString} FROM [{type.Name}] ";
List list = new List();
using (SqlConnection conn = new SqlConnection(strConn))
{
SqlCommand command = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
list = this.ReaderToList(reader);
}
return list;
}
publicint Update(T t) where T : BaseModel
{
int result = 0;
using (SqlConnection conn = new SqlConnection(strConn))
{
Type type = typeof(T);
var propArray = type.GetProperties().Where(p => p.Name != "Id");
string columnString = string.Join(",", propArray.Select(p => $"[{p.GetColumnName()}]=@{p.GetColumnName()}"));
var parameters = propArray.Select(p => new SqlParameter($"@{p.GetColumnName()}", p.GetValue(t) ?? DBNull.Value)).ToArray();
//必须参数化 否则引号? 或者值里面还有引号string strSQL = $"UPDATE [{type.Name}] SET {columnString} WHERE Id={t.Id}";
SqlCommand command = new SqlCommand(strSQL, conn);
command.Parameters.AddRange(parameters);
conn.Open();
result = command.ExecuteNonQuery();
}
return result;
}
private List ReaderToList(SqlDataReader reader) where T : BaseModel
{
Type type = typeof(T);
List list = new List();
while (reader.Read())//表示有数据 开始读 {
T t = (T)Activator.CreateInstance(type);
foreach (var prop in type.GetProperties())
{
object oValue = reader[prop.GetColumnName()];
if (oValue is DBNull)
oValue = null;
prop.SetValue(t, oValue);//除了guid和枚举 }
list.Add(t);
}
return list;
}
}
}
7、在Main()方法中调用
using FunApplication.DAL;
using FunApplication.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication
{
class Program
{
staticvoid Main(string[] args)
{
#region MyRegion
BaseDAL dal = new BaseDAL();
// 查询
Student student = dal.Query(2);
Console.WriteLine($"姓名:{student.Name},年龄:{student.Age},Email地址:{student.Email}");
Console.WriteLine("----------------------------");
// 查询所有
List list = dal.QueryAll();
Console.WriteLine($"集合个数:{list.Count}");
Console.WriteLine("----------------------------");
// 插入
Student studentIns = new Student()
{
Name = "小明",
Age = 20,
Sex = 2,
Email = "xiaoming@qq.com"
};
bool resultIns = dal.Insert(studentIns) > 0 ? true : false;
Console.WriteLine($"插入执行结果:{resultIns}");
Console.WriteLine("----------------------------");
// 更新
Student studentUpd = new Student()
{
Id = 1,
Name = "zhangsan1234",
Age = 20,
Sex = 2,
Email = "zhangsan1234@qq.com"
};
bool resultUpd = dal.Update(studentUpd) > 0 ? true : false;
Console.WriteLine($"更新执行结果:{resultUpd}");
Console.WriteLine("----------------------------");
// 删除bool resultDel = dal.Delete(3) > 0 ? true : false;
Console.WriteLine($"删除执行结果:{resultDel}");
#endregion
Console.ReadKey();
}
}
}
using FunApplication.AttributeExtend;
using FunApplication.IDAL;
using FunApplication.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication.DAL
{
publicclass FunBaseDAL : IBaseDAL
{
// 数据库链接字符串privatestaticstring strConn = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
publicint Delete(int id) where T : BaseModel
{
Type type = typeof(T);
string sql = $"delete from {type.Name} where Id=@Id";
Funcint> func = (SqlCommand command) =>
{
SqlParameter para = new SqlParameter("Id", id);
command.Parameters.Add(para);
return command.ExecuteNonQuery();
};
return ExcuteSqlint>(sql, func);
}
publicint Insert(T t) where T : BaseModel
{
int result = 0;
Type type = typeof(T);
var propArray = type.GetProperties().Where(p => p.Name != "Id");
string strSQL = "insert into Student Values (@Name,@Age,@Sex,@Email) ";
var parameters = propArray.Select(p => new SqlParameter($"@{p.GetColumnName()}", p.GetValue(t) ?? DBNull.Value)).ToArray();
Funcint> func = (SqlCommand command) =>
{
command.Parameters.AddRange(parameters);
return command.ExecuteNonQuery();
};
result = ExcuteSqlint>(strSQL, func);
return result;
}
public T Query(int id) where T : BaseModel
{
Type type = typeof(T);
string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]"));
string sql = $"SELECT {columnString} FROM [{type.Name}] WHERE Id=@Id";
T t = null;
DataTable dt = new DataTable();
Func func = (SqlCommand command) =>
{
SqlParameter para = new SqlParameter("@Id", id);
command.Parameters.Add(para);
SqlDataAdapter adapter = new SqlDataAdapter(command);
//SqlDataReader reader = command.ExecuteReader();
//List list = this.ReaderToList(reader); adapter.Fill(dt);
List list = ConvertToList(dt);
T tResult = list.FirstOrDefault();
return tResult;
};
t = ExcuteSql(sql, func);
return t;
}
public List QueryAll() where T : BaseModel
{
Type type = typeof(T);
string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]"));
string sql = $"SELECT {columnString} FROM [{type.Name}] ";
T t = null;
Func> func = (SqlCommand command) =>
{
SqlDataReader reader = command.ExecuteReader();
List list = this.ReaderToList(reader);
return list;
};
return ExcuteSql>(sql, func);
}
publicint Update(T t) where T : BaseModel
{
int result = 0;
Type type = typeof(T);
var propArray = type.GetProperties().Where(p => p.Name != "Id");
string columnString = string.Join(",", propArray.Select(p => $"[{p.GetColumnName()}]=@{p.GetColumnName()}"));
var parameters = propArray.Select(p => new SqlParameter($"@{p.GetColumnName()}", p.GetValue(t) ?? DBNull.Value)).ToArray();
//必须参数化 否则引号? 或者值里面还有引号string strSQL = $"UPDATE [{type.Name}] SET {columnString} WHERE Id={t.Id}";
Funcint> func = (SqlCommand command) =>
{
command.Parameters.AddRange(parameters);
return command.ExecuteNonQuery();
};
result = ExcuteSqlint>(strSQL, func);
return result;
}
//多个方法里面重复对数据库的访问 想通过委托解耦,去掉重复代码private T ExcuteSql(string sql, Func func)
{
using (SqlConnection conn = new SqlConnection(strConn))
{
using (SqlCommand command = new SqlCommand(sql, conn))
{
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
try
{
command.Transaction = sqlTransaction;
T tResult = func.Invoke(command);
sqlTransaction.Commit();
return tResult;
}
catch (Exception ex)
{
sqlTransaction.Rollback();
throw;
}
}
}
}
private List ReaderToList(SqlDataReader reader) where T : BaseModel
{
Type type = typeof(T);
List list = new List();
while (reader.Read())//表示有数据 开始读 {
T t = (T)Activator.CreateInstance(type);
foreach (var prop in type.GetProperties())
{
object oValue = reader[prop.GetColumnName()];
if (oValue is DBNull)
oValue = null;
prop.SetValue(t, oValue);//除了guid和枚举 }
list.Add(t);
}
reader.Close();
return list;
}
}
}
10、在Main()方法中调用
using FunApplication.DAL;
using FunApplication.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunApplication
{
class Program
{
staticvoid Main(string[] args)
{
#region 传统实现
//BaseDAL dal = new BaseDAL();//// 查询//Student student = dal.Query(2);
//Console.WriteLine($"姓名:{student.Name},年龄:{student.Age},Email地址:{student.Email}");
//Console.WriteLine("----------------------------");//// 查询所有//List list = dal.QueryAll();
//Console.WriteLine($"集合个数:{list.Count}");
//Console.WriteLine("----------------------------");//// 插入//Student studentIns = new Student()
//{
// Name = "小明",
// Age = 20,
// Sex = 2,
// Email = "xiaoming@qq.com"
//};
//bool resultIns = dal.Insert(studentIns) > 0 ? true : false;
//Console.WriteLine($"插入执行结果:{resultIns}");
//Console.WriteLine("----------------------------");//// 更新//Student studentUpd = new Student()
//{
// Id = 1,
// Name = "zhangsan1234",
// Age = 20,
// Sex = 2,
// Email = "zhangsan1234@qq.com"
//};
//bool resultUpd = dal.Update(studentUpd) > 1 ? true : false;
//Console.WriteLine($"更新执行结果:{resultUpd}");
//Console.WriteLine("----------------------------");//// 删除//bool resultDel = dal.Delete(5) > 1 ? true : false;
//Console.WriteLine($"删除执行结果:{resultDel}");#endregion#region 利用委托
// 查询
FunBaseDAL dal = new FunBaseDAL();
Student student = dal.Query(1);
Console.WriteLine($"姓名:{student.Name},年龄:{student.Age},Email地址:{student.Email}");
Console.WriteLine("----------------------------");
// 查询所有
List list = dal.QueryAll();
Console.WriteLine($"集合个数:{list.Count}");
Console.WriteLine("----------------------------");
// 插入
Student studentIns = new Student()
{
Name = "tom",
Age = 19,
Sex = 1,
Email = "tom@163.com"
};
bool resultIns = dal.Insert(studentIns) > 0 ? true : false;
Console.WriteLine($"插入执行结果:{resultIns}");
Console.WriteLine("----------------------------");
List list1 = dal.QueryAll();
Console.WriteLine($"插入后集合个数:{list1.Count}");
Console.WriteLine("----------------------------");
// 更新
Student studentUpd = new Student()
{
Id = 2,
Name = "马六123",
Age = 20,
Sex = 2,
Email = "maliu1234@qq.com"
};
bool resultUpd = dal.Update(studentUpd) > 0 ? true : false;
Console.WriteLine($"更新执行结果:{resultUpd}");
Console.WriteLine("----------------------------");
// 删除bool resultDel = dal.Delete(8) > 0 ? true : false;
Console.WriteLine($"删除执行结果:{resultDel}");
List list2 = dal.QueryAll();
Console.WriteLine($"删除后集合个数:{list2.Count}");
Console.WriteLine("----------------------------");
#endregion
Console.ReadKey();
}
}
}
////// 将DataTable转换成List
////////////private List ConvertToList(DataTable dt) where T:BaseModel
{
Type type = typeof(T);
List list = new List();
foreach(DataRow dr in dt.Rows)
{
T t = (T)Activator.CreateInstance(type);
foreach(PropertyInfo prop in type.GetProperties())
{
object value = dr[prop.GetColumnName()];
if(value is DBNull)
{
value = null;
}
prop.SetValue(t, value);
}
list.Add(t);
}
return list;
}