.NET Core Dapper操作mysql數據庫

前言

現在ORM盛行,市面上已經出現了N款不同的ORM套餐了。今天,我們不談EF,也不聊神馬黑馬,就說說 Dapper。如何在.NET Core中使用Dapper操作Mysql數據庫呢,讓我們跟隨鏡頭(手動下翻)一看究竟。

配置篇

俗話說得好,欲要善其事必先利其器。首先,我們要引入MySql.Data 的Nuget包。有人可能出現了黑人臉,怎麼引入。也罷,看在你骨骼驚奇的份上,我就告訴你,兩種方式:

第一種方式

Install-Package MySql.Data -Version 8.0.15

 複製上面命令行 在程序包管理控制檯中執行,什麼?你不知道什麼是程序包管理控制檯?OMG,也罷,看在你骨骼驚奇的份上,我就告訴你

 手點路徑:工具 → NuGet包管理器 → 程序包管理控制檯 

第二種方式

手點路徑:右鍵你需要引入包的項目的依賴項 → 管理NuGet程序包 → 瀏覽裏面輸入MySql.Data

 

直接安裝即可,因爲我已經安裝過了,所以這裏是卸載或者更新

同樣的方式你需要引入:

Microsoft.AspNetCore.All
MySql.Data.EntityFrameworkCore、
Dapper
Microsoft.Extensions.Configuration.Abstractions
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json

 

教學篇

玩兒過.NET Core 的都知道配置文件我們一般都放在appsettings.json 文件中,但是有個問題,如果我們使用數據庫連接字符串,直接存放明文的user name和password,真的安全嗎?這裏我們不對安全性做討論,我們在連接字符串中 用佔位符控制我們的多數據庫情況,然後用userName以及passWord充當我們密碼(後面會被替換掉),所以看起來是這個樣子:

 "ConnectionStrings": {
    "DefaultConnection": "server=服務器;port=端口號;database=regatta{0};SslMode=None;uid=userName;pwd=passWord;Allow User Variables=true"
  },

接下來,我們新建一個BaseRepository 用於讀取Configuration,以及設置MySqlConnection:

 

public class BaseRepository : IDisposable
    {
        public static IConfigurationRoot Configuration { get; set; }

        private MySqlConnection conn;

        public MySqlConnection GetMySqlConnection(int regattaId = 0, bool open = true,
            bool convertZeroDatetime = false, bool allowZeroDatetime = false)
        {
            IConfigurationBuilder builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");

            Configuration = builder.Build();
            

            string cs = Configuration.GetConnectionString("DefaultConnection");
            cs = regattaId == 0 ? string.Format(cs, string.Empty) : string.Format(cs, "_" + regattaId.ToString());

            cs = cs.Replace("userName", "真正的賬號").Replace("passWord", "真正的密碼");
            var csb = new MySqlConnectionStringBuilder(cs)
            {
                AllowZeroDateTime = allowZeroDatetime,
                ConvertZeroDateTime = convertZeroDatetime
            };
            conn = new MySqlConnection(csb.ConnectionString);
            return conn;
        }
public void Dispose()
{
if (conn != null && conn.State != System.Data.ConnectionState.Closed)
{
conn.Close();
}
}

}

好了,創建完畢,我們該如何使用呢,比方說 現在有個CrewManagerRepository類用於操作數據庫,我們只需要讓此類繼承BaseRepository ,示例如下

 

        /// <summary>
        /// 根據賽事Id、用戶Id獲取用戶基本信息
        /// </summary>
        /// <param name="regattaId">賽事Id</param>
        /// <param name="userId">用戶Id</param>
        /// <returns></returns>
        public async Task<實體對象> FindUserByAccount(int regattaId, int userId)
        {
            try
            {
                var cmdText =
                    @"select b.id_number as IdentifierId,b.isvalid as Isvalid,a.name as Name,a.userid as InternalId,a.sex as Sexual,a.sex as SexTypeId,a.age as Age,
                                c.isprofessional as IsProfessional,c.role_type as RoleTypeId,a.weight as Weight,a.height as Height, a.phone as PhoneNumber,a.thumb_image as ThubmnailImage,
                                a.image as Image,c.athlete_id as  AthleteId from 表1 a  left join 表2 b on a.userid=b.id 
                                left join 表3 c on b.id=c.centralid where a.userid=@userId;";
          //此處可以根據傳入的regattaId訪問不同的數據庫
using (var conn = GetMySqlConnection(regattaId)) { if (conn.State == ConnectionState.Closed) { await conn.OpenAsync(); } var memberModel = conn .Query<實體對象>(cmdText, new { userId = userId }, commandType: CommandType.Text) .FirstOrDefault(); return memberModel ?? new MemberDetail(); } } catch (Exception ex) { _logger.LogError(ex, "FindUserByAccount by Id Failed!"); throw; } }

 

那有同學可能有黑人臉出現了,如果需要事務呢(露出嘴角的微笑)?

public async Task<bool> DeleteXXX(int regattaId, int id, int userId)
        {
            var result = false;
            using (var conn = GetMySqlConnection(regattaId))
            {
                if (conn.State == ConnectionState.Closed)
                {
                    await conn.OpenAsync();
                }

                using (var transaction = conn.BeginTransaction())
                {
                    try
                    {
                        const string sqlDelClub =
                            @"delete from 表名 where 字段1=@clubId;
                              delete from 表名2 where 字段2=@clubId;
                              delete from 表名3 where 字段3=@userId and clubinfo_id=@clubId;";

                        await conn.QueryAsync(sqlDelClub, new
                        {
                            clubId = id,
                            userId = userId,
                        }, commandType: CommandType.Text);

                        transaction.Commit();

                        result = true;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        transaction.Rollback();
                        result = false;
                        throw;
                    }
                }

                return result;
            }
        }

這樣,用Transaction將執行代碼塊包起來,如果出現異常,在catch中 進行Rollback(回滾事務),就可以保證了數據的一致性。如果是高併發場景,可能還會需要用到鎖,這裏暫時不做延伸討論。

如果是返回集合,也很容易處理:

public async Task<List<實體>> GetClubsByUserId(int regattaId, int userId)
        {
            using (var conn = GetMySqlConnection(regattaId))
            {
                if (conn.State == ConnectionState.Closed)
                {
                    await conn.OpenAsync();
                }

                const string sql =
                    @"select b.club_id as id,c.name,c.image as ImageData,c.year,c.address,c.creator,c.description,b.contact ,b.phone,b.isvalid from 表1 a left join 表2 b on 
                      a.clubinfo_id=b.club_id left join 表3 c on 
                      b.clubbase_id=c.club_id where a.authorize_userid=@user_Id";
                List<實體> clubDetailList =
                    (await conn.QueryAsync<實體>(sql, new { user_Id = userId }, commandType: CommandType.Text))
                    .ToList();

                return clubDetailList;
            }
        }

關於Dapper的示例 本文就講到這兒,大家可以上官網瀏覽瞭解更多:

https://dapper-tutorial.net/

 

本文完

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章