赞
踩
前言:
在本系列第一篇《一步一步创建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
{
///
/// 博文实体类
///
public class Post
{
///
/// ID
///
public int Id { get; set; }
///
/// 标题
///
public string Title { get; set; }
///
/// 内容
///
public string Content { get; set; }
///
/// 作者ID
///
public string AuthorId { get; set; }
///
/// 作者姓名
///
public string AuthorName { get; set; }
///
/// 创建时间
///
public DateTime CreatedAt { get; set; }
///
/// 发布时间
///
public DateTime PublishedAt { get; set; }
///
/// 是否标识已删除
///
public bool IsDeleted { get; set; }
///
/// 是否允许展示
///
public bool AllowShow { get; set; }
///
/// 浏览量
///
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
{
///
/// 数据访问抽象基础类
///
public sealed class MySqlHelper
{
//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.
public static string connectionString = "连接字符串";
private MySqlHelper()
{
}
#region 公用方法
///
/// 得到最大值
///
///
///
///
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());
}
}
///
/// 是否存在
///
///
///
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;
}
}
///
/// 是否存在(基于MySqlParameter)
///
///
///
///
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语句
///
/// 执行SQL语句,返回影响的记录数
///
/// SQL语句
/// 影响的记录数
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;
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// 多条SQL语句
public static int ExecuteSqlTran(List 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;
}
}
}
///
/// 执行带一个存储过程参数的的SQL语句。
///
/// SQL语句
/// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加
/// 影响的记录数
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();
}
}
}
///
/// 执行带一个存储过程参数的的SQL语句。
///
/// SQL语句
/// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加
/// 影响的记录数
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();
}
}
}
///
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
///
/// SQL语句
/// 图像字节,数据库的字段类型为image的情况
/// 影响的记录数
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();
}
}
}
///
/// 执行一条计算查询结果语句,返回查询结果(object)。
///
/// 计算查询结果语句
/// 查询结果(object)
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;
}
}
}
}
///
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
///
/// 查询语句
/// MySqlDataReader
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;
}
}
///
/// 执行查询语句,返回DataSet
///
/// 查询语句
/// DataSet
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语句
///
/// 执行SQL语句,返回影响的记录数
///
/// SQL语句
/// 影响的记录数
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;
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])
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;
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])
public static int ExecuteSqlTran(System.Collections.Generic.List 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;
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])
public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List 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;
}
}
}
}
///
/// 执行多条SQL语句,实现数据库事务。
///
/// SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])
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;
}
}
}
}
///
/// 执行一条计算查询结果语句,返回查询结果(object)。
///
/// 计算查询结果语句
/// 查询结果(object)
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;
}
}
}
}
///
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
///
/// 查询语句
/// MySqlDataReader
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();
// }
}
///
/// 执行查询语句,返回DataSet
///
/// 查询语句
/// DataSet
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
{
///
/// 对其他语句无任何影响
///
None,
///
/// 当前语句必须为"select count(1) from .."格式,如果存在则继续执行,不存在回滚事务
///
WhenHaveContine,
///
/// 当前语句必须为"select count(1) from .."格式,如果不存在则继续执行,存在回滚事务
///
WhenNoHaveContine,
///
/// 当前语句影响到的行数必须大于0,否则回滚事务
///
ExcuteEffectRows,
///
/// 引发事件-当前语句必须为"select count(1) from .."格式,如果不存在则继续执行,存在回滚事务
///
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 ToList(this DataTable table) where T : class, new()
{
var obj = new T();
var tType = obj.GetType();
var list = new List();
//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()
.Select(item => new
{
Name = item.ColumnName,
Type = item.DataType
}).ToList();
foreach (var row in table.Rows.Cast())
{
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
{
///
/// POST表的数据库操作类
///
public class PostRepository
{
///
/// 根据ID查询
///
/// Post ID
///
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().FirstOrDefault();
return entity;
}
///
/// 查询所有数据
///
///
public List FindAll()
{
var ds = MySqlHelper.Query("SELECT * FROM tb_post");
return ds.Tables[0].ToList();
}
}
}
完善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;
}
Post find by id testPost id:@Model.Id
Post Title:@Model.Title
数据库连接
在Web.coinfig文件添加对应的数据库连接字符串:
如图:
修改项目[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数据连接成功了。
这篇文章一口气写下来实在是够长的啊,侧边的滚动条细成小蛮腰了,哈哈。。。
如果你喜欢本文,请点个赞以支持作者后续写得更好!!!
有问题欢迎留言反馈。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。