SqlSugar直接執行Sql
我的思路:
1、數據庫中寫好sql
2、用SqlSugar直接執行sql,獲取DataTable的數據
3、DataTable轉成List
class Program
{
static void Main(string[] args)
{
SqlSugarClient db = new SqlSugarClient(
new ConnectionConfig()
{
ConnectionString = "連接字符串***",
DbType = DbType.SqlServer,//設置數據庫類型
IsAutoCloseConnection = true,//自動釋放數據務,如果存在事務,在事務結束后釋放
InitKeyType = InitKeyType.Attribute //從實體特性中讀取主鍵自增列信息
});
var dt = db.Ado.GetDataTable("Sql語句***",
new List<SugarParameter>(){
new SugarParameter("@name","1") //參數
});
List<StudentModel> studentModels = new List<StudentModel>();
studentModels = ConvertToList(dt);
}
//DataTable轉成List
public static List<StudentModel> ConvertToList(DataTable dt)
{
// 定義集合
List<StudentModel> ts = new List<StudentModel>();
// 獲得此模型的類型
Type type = typeof(StudentModel);
//定義一個臨時變量
string tempName = string.Empty;
//遍歷DataTable中所有的數據行
foreach (DataRow dr in dt.Rows)
{
StudentModel t = new StudentModel();
// 獲得此模型的公共屬性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍歷該對象的所有屬性
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;//將屬性名稱賦值給臨時變量
//檢查DataTable是否包含此列(列名==對象的屬性名)
if (dt.Columns.ContainsKey(tempName))
{
// 判斷此屬性是否有Setter
if (!pi.CanWrite) continue;//該屬性不可寫,直接跳出
//取值
object value = dr[tempName];
//如果非空,則賦給對象的屬性
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
//對象添加到泛型集合中
ts.Add(t);
}
return ts;
}
}

