.NET Core Dapper操作mysql數(shù)據(jù)庫的實現(xiàn)方法
前言
現(xiàn)在ORM盛行,市面上已經(jīng)出現(xiàn)了N款不同的ORM套餐了。今天,我們不談EF,也不聊神馬黑馬,就說說 Dapper。如何在.NET Core中使用Dapper操作Mysql數(shù)據(jù)庫呢,讓我們跟隨鏡頭(手動下翻)一看究竟。
配置篇
俗話說得好,欲要善其事必先利其器。首先,我們要引入MySql.Data 的Nuget包。有人可能出現(xiàn)了黑人臉,怎么引入。也罷,看在你骨骼驚奇的份上,我就告訴你,兩種方式:
第一種方式
Install-Package MySql.Data -Version 8.0.15
復(fù)制上面命令行 在程序包管理控制臺中執(zhí)行,什么?你不知道什么是程序包管理控制臺?OMG,也罷,看在你骨骼驚奇的份上,我就告訴你
手點路徑:工具 → NuGet包管理器 → 程序包管理控制臺
第二種方式
手點路徑:右鍵你需要引入包的項目的依賴項 → 管理NuGet程序包 → 瀏覽里面輸入 MySql.Data
直接安裝即可,因為我已經(jīng)安裝過了,所以這里是卸載或者更新
同樣的方式你需要引入:
Microsoft.AspNetCore.All MySql.Data.EntityFrameworkCore、 Dapper Microsoft.Extensions.Configuration.Abstractions Microsoft.Extensions.Configuration.FileExtensions Microsoft.Extensions.Configuration.Json
教學(xué)篇
玩兒過.NET Core 的都知道配置文件我們一般都放在appsettings.json 文件中,但是有個問題,如果我們使用數(shù)據(jù)庫連接字符串,直接存放明文的user name和password,真的安全嗎?這里我們不對安全性做討論,我們在連接字符串中 用占位符控制我們的多數(shù)據(jù)庫情況,然后用userName以及passWord充當我們密碼(后面會被替換掉),所以看起來是這個樣子:
"ConnectionStrings": { "DefaultConnection": "server=服務(wù)器;port=端口號;database=regatta{0};SslMode=None;uid=userName;pwd=passWord;Allow User Variables=true" },
接下來,我們新建一個BaseRepository 用于讀取Configuration,以及設(shè)置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(); } } }
好了,創(chuàng)建完畢,我們該如何使用呢,比方說 現(xiàn)在有個CrewManagerRepository類用于操作數(shù)據(jù)庫,我們只需要讓此類 繼承BaseRepository , 示例如下
/// <summary> /// 根據(jù)賽事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;"; //此處可以根據(jù)傳入的regattaId訪問不同的數(shù)據(jù)庫 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; } }
那有同學(xué)可能有黑人臉出現(xiàn)了,如果需要事務(wù)呢(露出嘴角的微笑)?
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將執(zhí)行代碼塊包起來,如果出現(xiàn)異常,在catch中 進行Rollback(回滾事務(wù)),就可以保證了數(shù)據(jù)的一致性。如果是高并發(fā)場景,可能還會需要用到鎖,這里暫時不做延伸討論。
如果是返回集合,也很容易處理:
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; } }
關(guān)于Dapper的示例 本文就講到這兒,大家可以上官網(wǎng)瀏覽了解更多:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ASP.NET2.0 WebRource,開發(fā)微調(diào)按鈕控件
ASP.NET2.0 WebRource,開發(fā)微調(diào)按鈕控件...2006-09-09ASP.NET沒有魔法_ASP.NET MVC 模型驗證方法
下面小編就為大家分享一篇ASP.NET沒有魔法_ASP.NET MVC 模型驗證方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02asp.net中使用cookie與md5加密實現(xiàn)記住密碼功能的實現(xiàn)代碼
雖然.net內(nèi)置了登陸控件,有記住密碼的功能,但還是想自己實踐一下,以下代碼主要應(yīng)用了COOKIE,包括安全加密的過程等2013-02-02SQLServer 在Visual Studio的2種連接方法
這篇文章介紹了SQLServer 在Visual Studio的2種連接方法,有需要的朋友可以參考一下2013-09-09詳解ASP.NET Core MVC 源碼學(xué)習(xí):Routing 路由
本篇文章主要介紹了詳解ASP.NET Core MVC 源碼學(xué)習(xí):Routing 路由 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03c# static 靜態(tài)數(shù)據(jù)成員
靜態(tài)成員屬于類所有,為各個類的實例所公用,無論類創(chuàng)建了幾多實例,類的靜態(tài)成員在內(nèi)存中只占同一塊區(qū)域。2009-06-06MVC4制作網(wǎng)站教程第三章 添加用戶組操作3.2
這篇文章主要為大家詳細介紹了MVC4制作網(wǎng)站教程,添加用戶組功能的實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-08-08