前言: 在本系列第一篇《 "一步一步創建ASP.NET MVC5程式\[Repository+Autofac+Automapper+SqlSugar\" ][1]》中,我為大家介紹了搭建空白解決方案以及在此解決方案中創建目錄和對應的項目。本篇將和大家一起學習在項目中使用Nuget引入.NET對應的M ...
前言:
在本系列第一篇《一步一步創建ASP.NET MVC5程式[Repository+Autofac+Automapper+SqlSugar](一)》中,我為大家介紹了搭建空白解決方案以及在此解決方案中創建目錄和對應的項目。本篇將和大家一起學習在項目中使用Nuget引入.NET對應的MySql.Data程式包,以及使用傳統的Ado.NET連接MySQL資料庫,實現一個簡單的查詢並將數據轉換成泛型對象的操作。
本篇知識要點
- Nuget程式包管理工具;
- MySQLHelper幫助類庫;
- Ado.NET
- 泛型
創建實體及工具類
- 在TsBlog.Domain項目中新建文件夾,命名為:Entities,再在此文件夾中添加實體類,命名為:Post.cs,打開Post.cs文件,創建以下屬性/成員:
using System;
namespace TsBlog.Domain.Entities
{
/// <summary>
/// 博文實體類
/// </summary>
public class Post
{
/// <summary>
/// ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 標題
/// </summary>
public string Title { get; set; }
/// <summary>
/// 內容
/// </summary>
public string Content { get; set; }
/// <summary>
/// 作者ID
/// </summary>
public string AuthorId { get; set; }
/// <summary>
/// 作者姓名
/// </summary>
public string AuthorName { get; set; }
/// <summary>
/// 創建時間
/// </summary>
public DateTime CreatedAt { get; set; }
/// <summary>
/// 發佈時間
/// </summary>
public DateTime PublishedAt { get; set; }
/// <summary>
/// 是否標識已刪除
/// </summary>
public bool IsDeleted { get; set; }
/// <summary>
/// 是否允許展示
/// </summary>
public bool AllowShow { get; set; }
/// <summary>
/// 瀏覽量
/// </summary>
public int ViewCount { get; set; }
}
}
如圖:
- 在項目TsBlog.Repositories中創建新的類,命名為:MySqlHelper.cs,此類用以封裝.NET對MySQL資料庫的底層操作,併在MySqlHelper.cs文件中添加如下代碼:
using MySql.Data.MySqlClient;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace TsBlog.Repositories
{
/// <summary>
/// 數據訪問抽象基礎類
/// </summary>
public sealed class MySqlHelper
{
//資料庫連接字元串(web.config來配置),可以動態更改connectionString支持多資料庫.
public static string connectionString = "連接字元串";
private MySqlHelper()
{
}
#region 公用方法
/// <summary>
/// 得到最大值
/// </summary>
/// <param name="FieldName"></param>
/// <param name="TableName"></param>
/// <returns></returns>
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 是否存在(基於MySqlParameter)
/// </summary>
/// <param name="strSql"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
#endregion
#region 執行簡單SQL語句
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
public static int ExecuteSqlByTime(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
public static int ExecuteSqlTran(List<String> SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
MySqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
int count = 0;
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return 0;
}
}
}
/// <summary>
/// 執行帶一個存儲過程參數的的SQL語句。
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <param name="content">參數內容,比如一個欄位是格式複雜的文章,有特殊符號,可以通過這個方式添加</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 執行帶一個存儲過程參數的的SQL語句。
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <param name="content">參數內容,比如一個欄位是格式複雜的文章,有特殊符號,可以通過這個方式添加</param>
/// <returns>影響的記錄數</returns>
public static object ExecuteSqlGet(string SQLString, string content)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(SQLString, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向資料庫里插入圖像格式的欄位(和上面情況類似的另一種實例)
/// </summary>
/// <param name="strSQL">SQL語句</param>
/// <param name="fs">圖像位元組,資料庫的欄位類型為image的情況</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object GetSingle(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
public static object GetSingle(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 執行查詢語句,返回MySqlDataReader ( 註意:調用該方法後,一定要對MySqlDataReader進行Close )
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string strSQL)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
try
{
connection.Open();
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
public static DataSet Query(string SQLString, int Times)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.SelectCommand.CommandTimeout = Times;
command.Fill(ds, "ds");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region 執行帶參數的SQL語句
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">SQL語句的哈希表(key為sql語句,value是該語句的MySqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
//迴圈
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">SQL語句的哈希表(key為sql語句,value是該語句的MySqlParameter[])</param>
public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int count = 0;
//迴圈
foreach (CommandInfo myDE in cmdList)
{
string cmdText = myDE.CommandText;
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
{
if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
{
trans.Rollback();
return 0;
}
object obj = cmd.ExecuteScalar();
bool isHave = false;
if (obj == null && obj == DBNull.Value)
{
isHave = false;
}
isHave = Convert.ToInt32(obj) > 0;
if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
{
trans.Rollback();
return 0;
}
if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
{
trans.Rollback();
return 0;
}
continue;
}
int val = cmd.ExecuteNonQuery();
count += val;
if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
{
trans.Rollback();
return 0;
}
cmd.Parameters.Clear();
}
trans.Commit();
return count;
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">SQL語句的哈希表(key為sql語句,value是該語句的MySqlParameter[])</param>
public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int indentity = 0;
//迴圈
foreach (CommandInfo myDE in SQLStringList)
{
string cmdText = myDE.CommandText;
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">SQL語句的哈希表(key為sql語句,value是該語句的MySqlParameter[])</param>
public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
conn.Open();
using (MySqlTransaction trans = conn.BeginTransaction())
{
MySqlCommand cmd = new MySqlCommand();
try
{
int indentity = 0;
//迴圈
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (MySqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object GetSingle(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// 執行查詢語句,返回MySqlDataReader ( 註意:調用該方法後,一定要對MySqlDataReader進行Close )
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
// finally
// {
// cmd.Dispose();
// connection.Close();
// }
}
/// <summary>
/// 執行查詢語句,返回DataSet
/// </summary>
/// <param name="SQLString">查詢語句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (MySqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
#endregion
}
public enum EffentNextType
{
/// <summary>
/// 對其他語句無任何影響
/// </summary>
None,
/// <summary>
/// 當前語句必須為"select count(1) from .."格式,如果存在則繼續執行,不存在回滾事務
/// </summary>
WhenHaveContine,
/// <summary>
/// 當前語句必須為"select count(1) from .."格式,如果不存在則繼續執行,存在回滾事務
/// </summary>
WhenNoHaveContine,
/// <summary>
/// 當前語句影響到的行數必須大於0,否則回滾事務
/// </summary>
ExcuteEffectRows,
/// <summary>
/// 引發事件-當前語句必須為"select count(1) from .."格式,如果不存在則繼續執行,存在回滾事務
/// </summary>
SolicitationEvent
}
public class CommandInfo
{
public object ShareObject = null;
public object OriginalData = null;
event EventHandler _solicitationEvent;
public event EventHandler SolicitationEvent
{
add
{
_solicitationEvent += value;
}
remove
{
_solicitationEvent -= value;
}
}
public void OnSolicitationEvent()
{
if (_solicitationEvent != null)
{
_solicitationEvent(this, new EventArgs());
}
}
public string CommandText;
public System.Data.Common.DbParameter[] Parameters;
public EffentNextType EffentNextType = EffentNextType.None;
public CommandInfo()
{
}
public CommandInfo(string sqlText, SqlParameter[] para)
{
this.CommandText = sqlText;
this.Parameters = para;
}
public CommandInfo(string sqlText, SqlParameter[] para, EffentNextType type)
{
this.CommandText = sqlText;
this.Parameters = para;
this.EffentNextType = type;
}
}
}
添加代碼後,Visual Studio編輯器會提示如下圖的錯誤,如圖:
說明在項目中還沒有引入MySql.Data這個程式包,現在我們會再一次用到Nuget程式包管理工具,在此項目的引用[References]選擇上右鍵單擊,選擇[Manage Nuget Packages],進入到項目的Nuget程式包管理界面,搜索MySql.Data,在查找到的結果中選擇MySql.Data,同時選擇版本(本系列使用的是MySql.Data 6.9.9),點擊"Install"進行安裝,完成後,我們回到MySqlHelper.cs文件,引入MySql.Data.MySqlClient的命名空間:
using MySql.Data.MySqlClient;
到此,MySqlHelper.cs這個MySql的幫助類庫就創建完成了。但為了本文後續用的數據轉換,我們再在此項目中創建一個新的類文件,命名為:DataConverter.cs,將此類寫成靜態的類並創建一個從DataTable轉換到泛型對象的靜態擴展方法,編寫如下代碼:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace TsBlog.Repositories
{
public static class DataConverter
{
public static List<T> ToList<T>(this DataTable table) where T : class, new()
{
var obj = new T();
var tType = obj.GetType();
var list = new List<T>();
//Define what attributes to be read from the class
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
//Read Attribute Names and Types
var objFieldNames = typeof(T).GetProperties(flags)
.Select(item => new
{
item.Name,
Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType
}).ToList();
//Read Datatable column names and types
var dtlFieldNames = table.Columns.Cast<DataColumn>()
.Select(item => new
{
Name = item.ColumnName,
Type = item.DataType
}).ToList();
foreach (var row in table.Rows.Cast<DataRow>())
{
foreach (var prop in objFieldNames)
{
if (!dtlFieldNames.Any(x => x.Name.Equals(prop.Name, StringComparison.CurrentCultureIgnoreCase)))
{
continue;
}
var propertyInfo = tType.GetProperty(prop.Name);
var rowValue = row[prop.Name];
if (propertyInfo == null) continue;
var t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
var safeValue = (rowValue == null || DBNull.Value.Equals(rowValue)) ? null : Convert.ChangeType(rowValue, t);
propertyInfo.SetValue(obj, safeValue, null);
}
list.Add(obj);
}
return list;
}
}
}
到此,我們的準備工作完成得差不多了,接下來創建數據讀取相關的操作。
創建Repository類
在項目[TsBlog.Repositories]中,添加一個新的類文件,命名為:PostRepository.cs ,我們在這個類文件中進行關於博文的資料庫讀寫等操作(註:最開始我們以Ado.net的方式來操作資料庫,ORM將在後續的文章中逐步引用並完成項目的重構和優化),代碼如下:
PostRepository.cs
using MySql.Data.MySqlClient;
using System.Collections.Generic;
using System.Linq;
using TsBlog.Domain.Entities;
namespace TsBlog.Repositories
{
/// <summary>
/// POST表的資料庫操作類
/// </summary>
public class PostRepository
{
/// <summary>
/// 根據ID查詢
/// </summary>
/// <param name="id">Post ID</param>
/// <returns></returns>
public Post FindById(int id)
{
var ds = MySqlHelper.Query("SELECT * FROM tb_post WHERE Id=@Id", new MySqlParameter("@Id",id));
var entity = ds.Tables[0].ToList<Post>().FirstOrDefault();
return entity;
}
/// <summary>
/// 查詢所有數據
/// </summary>
/// <returns></returns>
public List<Post> FindAll()
{
var ds = MySqlHelper.Query("SELECT * FROM tb_post");
return ds.Tables[0].ToList<Post>();
}
}
}
完善View層
修改控制器
首先,我們進入到項目[TsBlog.Frontend],打開控制器[HomeController.cs],為我們測試數據讀取功能添加一個Action,命名為:Post,修改後的HomeController.cs文件代碼為:
HomeController.cs
using System.Web.Mvc;
using TsBlog.Repositories;
namespace TsBlog.Frontend.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Post()
{
var postRepository = new PostRepository();
var post = postRepository.FindById(1);
return View(post);
}
}
}
註意:引用TsBlog.Domain和TsBlog.Repositories這兩個程式集
創建視圖
再在視圖中添加對應的視圖Post.cshtml文件:
@model TsBlog.Domain.Entities.Post
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Post find by id test</title>
</head>
<body>
<div>
<p>Post id:@Model.Id</p>
<p>Post Title:@Model.Title</p>
</div>
</body>
</html>
資料庫連接
在Web.coinfig文件添加對應的資料庫連接字元串:
<connectionStrings>
<add name="TsBlogMySQLDb" connectionString="Server=localhost;Database=tsblog;UID=root;Password=123456;Allow User Variables=True;AllowZeroDateTime=True;ConvertZeroDateTime=True" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
如圖:
修改項目[TsBlog.Repositories]中的MySqlHelper.cs文件的資料庫連接配置:
public static string ConnectionString = ConfigurationManager.ConnectionStrings["TsBlogMySQLDb"].ConnectionString;
創建資料庫和表
打開MySql管理工具,執行以下Sql腳本,創建資料庫、數據表以及導入測試數據:
CREATE DATABASE IF NOT EXISTS `tsblog`
USE `tsblog`;
/*Table structure for table `tb_post` */
DROP TABLE IF EXISTS `tb_post`;
CREATE TABLE `tb_post` (
`Id` int(12) NOT NULL AUTO_INCREMENT,
`Title` varchar(255) DEFAULT '' COMMENT '標題',
`Content` text COMMENT '內容',
`AuthorId` int(6) DEFAULT '0' COMMENT '作者ID',
`AuthorName` varchar(50) DEFAULT '' COMMENT '作者姓名',
`CreatedAt` datetime DEFAULT NULL COMMENT '創建時間',
`PublishedAt` datetime DEFAULT NULL COMMENT '發佈時間',
`IsDeleted` bit(1) DEFAULT b'0' COMMENT '是否標識已刪除[0:否,1:是],預設值:0',
`AllowShow` bit(1) DEFAULT b'1' COMMENT '是否允許展示[0:否,1:是],預設值:1',
`ViewCount` int(10) DEFAULT '0' COMMENT '瀏覽量',
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*Data for the table `tb_post` */
insert into `tb_post`(`Id`,`Title`,`Content`,`AuthorId`,`AuthorName`,`CreatedAt`,`PublishedAt`,`IsDeleted`,`AllowShow`,`ViewCount`) values
(1,'Title','Clean content',0,'',NULL,NULL,'\0','1',0);
到這裡,看上去我們的配置都完成了,將項目[TsBlog.Frontend]設置為啟動項,按F5運行,會得到如下的錯誤:
是因為上一篇中把多餘的程式包給移除了,包括jquery,但ASP.NET MVC 5自動為我們開啟了壓縮功能,所以報錯。先暫時把壓縮功能關閉掉,打開Global.asax,我們看到的文件代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace TsBlog.Frontend
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
註釋掉壓縮配置語句:
using System.Web.Mvc;
using System.Web.Routing;
namespace TsBlog.Frontend
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
好,再按F5運行程式,打開地址:http://localhost:54739/home/post,如果得到如圖的界面:
那麼,基於Ado.net的MySql數據連接成功了。
這篇文章一口氣寫下來實在是夠長的啊,側邊的滾動條細成小蠻腰了,哈哈。。。
如果你喜歡本文,請點個贊以支持作者後續寫得更好!!!
有問題歡迎留言反饋。
本文同步發表至 圖享網 《一步一步創建ASP.NET MVC5程式[Repository+Autofac+Automapper+SqlSugar](一)》