約束 public abstract class BaseModel { public int Id { get; set; } } 連接字元串 public static readonly string Customers = ConfigurationManager.ConnectionStri ...
約束
public abstract class BaseModel
{
public int Id { get; set; }
}
連接字元串
public static readonly string Customers = ConfigurationManager.ConnectionStrings["Customers"].ToString();
通用資料庫字元串
public class SqlBuilder<T> where T : BaseModel
{
public static readonly string FindSql = null;
public static readonly string DeleteSql = null;
public static readonly string FindAllSql = null;
public static readonly string UpdateSql = null;
static SqlBuilder()
{
Type type = typeof(T);
FindSql = $"SELECT {string.Join(",", type.GetProperties().Select(a => $"[{a.Name}]")) } FROM [{type.Name}] where Id=@Id";
DeleteSql = $"Delete from [{type.Name}] where Id=@Id"; ;
FindAllSql = $"SELECT {string.Join(",", type.GetProperties().Select(a => $"[{a.Name}]")) } FROM [{type.Name}]";
UpdateSql = $"update [{type.Name}] set {string.Join(",", type.GetProperties().Where(a => !a.Name.Equals("Id")).Select(a => $"[{a.Name}]=@ {a.Name}"))} where Id =@Id";
}
}
一:添加
public bool Add<T>(T t) where T : BaseModel
{
Type type = typeof(T);
object oCompany = Activator.CreateInstance(type);
// Id 是自動增長的,sql語句中應該去除Id的欄位
// GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) 過濾掉繼承自父類的屬性
string props = string.Join(",", type.GetProperties().Where(p => !p.Name.Equals("Id")).Select(a => $"[{a.Name}]"));//獲取屬性名不等於id的所有屬性數組
string paraValues = string.Join(",", type.GetProperties().Where(p => !p.Name.Equals("Id")).Select(a => $"@[{a.Name}]"));//獲取屬性名不等於id的所有參數化數組
string sql = $"Insert [{type.Name}] ({props}) values({paraValues})";
var parameters = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Select(item => new SqlParameter()
{
ParameterName = $"@{item.Name}",
SqlValue = $"{item.GetValue(t)}"
});
//在拼接sql語句的時候,儘管ID 是Int類型,還是建議大家使用Sql語句參數化 (防止sql註入)
using (SqlConnection connection = new SqlConnection(Customers))
{
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Parameters.AddRange(parameters.ToArray());
connection.Open();
return sqlCommand.ExecuteNonQuery() > 0;
}
}
二:刪除
public bool Delete<T>(T t) where T : BaseModel
{
Type type = t.GetType();
string sql = SqlBuilder<T>.DeleteSql;
//string sql = $"Delete from [{type.Name}] where Id=@Id";
using (SqlConnection connection = new SqlConnection(Customers))
{
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Parameters.Add(new SqlParameter("@Id", t.Id));
connection.Open();
return sqlCommand.ExecuteNonQuery() > 0;
}
}
三:修改
public bool Update<T>(T t) where T : BaseModel
{
Type type = typeof(T);
object oCompany = Activator.CreateInstance(type);
//string sql = $"update [{type.Name}] set {string.Join(",", type.GetProperties().Where(a => !a.Name.Equals("Id")).Select(a => $"[{a.Name}]=@ {a.Name}"))} where Id =@Id";
string sql = SqlBuilder<T>.UpdateSql;
var parameters = type.GetProperties().Select(item => new SqlParameter()
{
ParameterName = $"@{item.Name}",
SqlValue = $"{item.GetValue(t)}"
});
// 在拼接sql語句的時候,儘管ID 是Int類型,還是建議大家使用Sql語句參數化防止sql註入)
using (SqlConnection connection = new SqlConnection(Customers))
{
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Parameters.AddRange(parameters.ToArray());
connection.Open();
return sqlCommand.ExecuteNonQuery() > 0;
}
}
四:查詢
//根據id查詢
public T Find<T>(int id) where T : BaseModel
{
Type type = typeof(T);
object oCompany = Activator.CreateInstance(type);
//string sql = $"SELECT {string.Join(",", type.GetProperties().Select(a => $"[{a.Name}]")) } FROM [{type.Name}] where Id=@Id";
string sql = SqlBuilder<T>.FindSql;
// 在拼接sql語句的時候,儘管ID 是Int類型,還是建議大家使用Sql語句參數化 (防止sql註入)
using (SqlConnection connection = new SqlConnection(Customers))
{
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Parameters.Add(new SqlParameter("@Id", id));
connection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.Read())
{
ReaderToList(type, oCompany, reader);
return (T)oCompany;
}
else
{
return null;
}
}
}
//查詢所有
public List<T> FindAll<T>() where T : BaseModel
{
Type type = typeof(T);
//string sql = $"SELECT {string.Join(",", type.GetProperties().Select(a => $"[{a.Name}]")) } FROM [{type.Name}]";
string sql = SqlBuilder<T>.FindAllSql;
using (SqlConnection connection = new SqlConnection(Customers))
{
SqlCommand sqlCommand = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
List<T> datalist = new List<T>();
while (reader.Read())
{
object oCompany = Activator.CreateInstance(type);
ReaderToList(type, oCompany, reader);
datalist.Add((T)oCompany);
}
return datalist;
}
}
//私有函數封裝通用代碼,引用類型可以不用返回
private static void ReaderToList(Type type, object oCompany, SqlDataReader reader)
{
foreach (var prop in type.GetProperties())
{
prop.SetValue(oCompany, reader[prop.Name] is DBNull ? null : reader[prop.Name]);
}
}