在之前,我简单的介绍过在.net core中使用Mongodb(见文章《.Net Core系列教程(三)——使用Mongodb》),也使用过PostgreSQL(但是没有写文章介绍怎么使用,只是在文章《.Net Core系列教程(一)——环境搭建》中简单介绍过如何安装)。当然,我的文章质量都不高,只是把自己平时遇到的问题记录下来,很多问题是自己经历过之后在网上苦苦的寻找答案但都不适用或者不明了的情况下,自己摸索出来的解决方案,这也算是防止自己再次误入坑,也给遇到同样问题的朋友一点帮助吧。
下面说下怎样在.net core中使用MySQL,这个问题网上随便一搜有很多,我的当然也是从网上搜索来的,只是用自己的语言再次整理下而已。
在使用MySQL时,需要使用到MySQL的驱动,之前MySQL官方没有出驱动的时候,需要使用第三方的,不过现在有官方的驱动,还是尽量使用官方的吧,我这里也以官方的为准。另外还用到了Dapper这个小型ORM,这两个都可以通过Nuget来安装。需要注意的是,MySQL.Data需要安装最新版的(现在是6.10.3-rc版),旧版本不支持.net core 2.0
先在appsettings.json文件中,添加数据库的配置:

  "ConnectionStrings": {
    "MySqlConnection": "server=127.0.0.1;userid=root;pwd=root's password;port=3306;database=database's name;sslmode=none;Charset=utf8;"
  }

之后,增加数据库连接的Model类:

    public class ConnectionStrings
    {
        public string MySqlConnection { get; set; }        
    }

在Startup.cs文件中的ConfigureServices方法里,在services.AddMvc();之前增加添加调用:

services.Configure<Models.ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));

这样就会把appsettings.json中的数据库连接配置注入到Models.ConnectionStrings实体类中。
在控制器中,添加:
private readonly IOptions<Models.ConnectionStrings> _settings;
之后控制器的构造函数:

        public NewsController(IOptions<Models.ConnectionStrings> settings)
        {
            _settings = settings;
        }

这里我是直接把数据库连接的实体类传给了DAL层,这样写:

        public NewsController(IOptions<Models.ConnectionStrings> settings)
        {
            _settings = new BLL.ServiceImp.News(settings.Value);
        }

其中的settings.Value就是数据库连接实体类了

之后在DAL层中使用,同时也附带了几个数据库操作的实例:

        private string ConnString;
        public News(Models.ConnectionStrings Connection)
        {
            ConnString = Connection.MySqlConnection;
        }


        /// <summary>
        /// 取前top条新闻
        /// </summary>
        /// <returns></returns>
        public async Task<Models.ResultModel<List<Models.News>>> Newslatest(int top)
        {
            Models.ResultModel<List<Models.News>> result = new ResultModel<List<Models.News>>();

            using (var Conn = new MySqlConnection(ConnString))
            {
                string sql = "select Id,title,datetime,writer,remark,body,cid,status,isimage,thumb,category from news where status=1 order by datetime desc limit 0,@top";
                var data = await Conn.QueryAsync<Models.News>(sql, new { top = top });
                if(data.Count()>0)
                {
                    result.code = 0;
                    result.status = true;
                    result.message = "OK";
                    result.data = data.AsList();
                }
            }

            return result;
        }

        /// <summary>
        /// 取单条
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Models.ResultModel<Models.News>> Detail(int id)
        {
            Models.ResultModel<Models.News> result = new ResultModel<Models.News>();
            using (var Conn =  new MySqlConnection(ConnString))
            {
                string sql = "select n.Id,title,datetime,writer,remark,body,cid,status,isimage,thumb,c.category from news n left join category c on n.cid=c.id where n.Id=@id";
                var res = await Conn.QueryAsync<Models.News>(sql, new { id = id });
                var data = res.SingleOrDefault();  //注意这里
                result.code = -404;
                result.message = "没有找到该条新闻";
                if (data != null)
                {
                    result.status = true;
                    result.message = "OK";
                    result.code = 0;
                    result.data = data;
                }
                else
                {
                    result.status = false;
                    result.code = -404;
                    result.message = "没有找到该条新闻";
                }
            }
            return result;
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Models.ResultModel<object>> Delete(int id)
        {
            Models.ResultModel<object> result = new ResultModel<object>();
            using (var Conn = new MySqlConnection(ConnString))
            {
                string sql = "delete from news where Id=@id";
                var res = await Conn.ExecuteAsync(sql, new { id = id });
                result.status = res > 0;
                if (result.status)
                {
                    result.code = 0;
                    result.message = "success";
                }
            }

            return result;
        }


        /// <summary>
        /// 使用事务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Models.ResultModel<object>> DeleteCategory(int id)
        {
            Models.ResultModel<object> result = new ResultModel<object>();

            using (var Conn = new MySqlConnection(ConnString))
            {
                Conn.Open();  //注意这里,使用事务时,需要先open
                using (IDbTransaction transaction = Conn.BeginTransaction())
                {
                    try
                    {
                        string sql = "update news set cid=0 where cid=@id;delete from category where Id=@id;";   //删除分类,同时把该分类下的新闻移动到默认分类下
                        var res = await Conn.ExecuteAsync(sql, new { id = id });
                        transaction.Commit();   //提交事务
                        result.status = res > 0;
                        if (result.status)
                        {
                            result.code = 0;
                            result.message = "success";
                        }
                        else
                        {
                            transaction.Rollback(); //删除失败,回滚
                        }
                    }
                    catch
                    {
                        transaction.Rollback(); //出现异常,回滚
                    }
                }
                Conn.Close();   
                
            }
            return result;
        }

以上。

Last modification:May 13, 2018
如果觉得我的文章对你有用,请随意赞赏