创建一个通用的数据访问层 (DAL) 类,让所有需要操作数据库的 DAL 类都继承这个基类,以实现通用的增删改查方法。下面是一个简单的示例展示如何实现这样的通用基类:
public class BaseDal<T> where T : class
{
protected string connectionString; // 数据库连接字符串
public BaseDal(string connectionString)
{
this.connectionString = connectionString;
}
public void Insert(T entity)
{
string tableName = typeof(T).Name; // 获取表名
string insertQuery = $"INSERT INTO {tableName} ({GetColumns()}) VALUES ({GetParams()})";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(insertQuery, connection))
{
SetParameters(command, entity);
command.ExecuteNonQuery();
}
}
}
public void Update(T entity)
{
string tableName = typeof(T).Name; // 获取表名
string updateQuery = $"UPDATE {tableName} SET {GetUpdateParams()} WHERE Id = @Id";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(updateQuery, connection))
{
SetParameters(command, entity);
command.ExecuteNonQuery();
}
}
}
public void Delete(int id)
{
string tableName = typeof(T).Name; // 获取表名
string deleteQuery = $"DELETE FROM {tableName} WHERE Id = @Id";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(deleteQuery, connection))
{
command.Parameters.AddWithValue("@Id", id);
command.ExecuteNonQuery();
}
}
}
// 获取实体类的所有属性名
private string GetColumns()
{
var properties = typeof(T).GetProperties().Where(p => p.Name != "Id"); // 排除 Id 属性
return string.Join(", ", properties.Select(p => p.Name));
}
// 获取参数列表
private string GetParams()
{
var properties = typeof(T).GetProperties().Where(p => p.Name != "Id"); // 排除 Id 属性
return string.Join(", ", properties.Select(p => "@" + p.Name));
}
// 获取更新参数列表
private string GetUpdateParams()
{
var properties = typeof(T).GetProperties().Where(p => p.Name != "Id"); // 排除 Id 属性
return string.Join(", ", properties.Select(p => $"{p.Name} = @{p.Name}"));
}
// 设置参数
private void SetParameters(SqlCommand command, T entity)
{
var properties = typeof(T).GetProperties().Where(p => p.Name != "Id"); // 排除 Id 属性
foreach (var property in properties)
{
command.Parameters.AddWithValue("@" + property.Name, property.GetValue(entity));
}
}
}
在这个示例中,BaseDal<T>
是一个泛型基类,其中包含了通用的增删改方法。在这个基类中,我们使用了反射来获取实体类的属性,并根据属性动态生成 SQL 语句和设置参数。其他需要操作数据库的 DAL 类可以继承这个基类,从而实现通用的增删改查操作。