.netcore mysql_.netcore基于mysql的codefirst

.netcore基于mysql的codefirst

此文僅是對于netcore基于mysql的簡單的codefirst實現的簡單記錄。示例為客服系統消息模板的增刪改查實現

第一步、創建實體項目,并在其中建立對應的實體類,以及數據庫訪問類

須引入Pomelo.EntityFrameworkCore.MySql和Microsoft.EntityFrameworkCore

///

///消息模板///

public classMessatgeTemplate

{///

///id///

[Key]public System.Guid Id { get; set; }///

///名稱///

[MaxLength(250)]public string Name { get; set; }///

///關鍵字///

[MaxLength(500)]public string Keywords { get; set; }///

///內容///

public string Content { get; set; }///

///語言///

[MaxLength(80)]public string CultureCode { get; set; }///

///類別///

[MaxLength(250)]public string Category { get; set; }///

///備注信息///

public string Remark { get; set; }///

///是否啟用///

public bool Enabled { get; set; }///

///創建時間///

public DateTime Created { get; set; }///

///最近修改時間///

public DateTime LastModified { get; set; }

}

///

///

///

public classCustomerServiceContext : DbContext

{public CustomerServiceContext(DbContextOptionsoptions)

:base(options)

{

}///

///配置///

///

protected override voidOnConfiguring(DbContextOptionsBuilder optionsBuilder)

{base.OnConfiguring(optionsBuilder);

}public virtual DbSet MessatgeTemplate { get; set; }

}

第二步、創建業務服務項目,添加對應的業務處理類

///

///客服業務統一接口///

public interfaceICustomerServicerSerice

{

}

///

///模板業務類///

public classMessageTemplateService : ICustomerServicerSerice

{privateCustomerServiceContext _CustomerServiceContext;publicMessageTemplateService(CustomerServiceContext customerServiceContext)

{this._CustomerServiceContext =customerServiceContext;

}///

///創建模板///

public voidCreateMessageTemplate()

{//todo create

}///

///修改模板///

public voidModifyMessageTemplate()

{//TODO modified

}///

///獲取模板///

///

public ListGetMessageTemplate()

{//TODO根據傳入參數查詢模板

return null;

}///

///刪除///

public voidDeleteMessageTemplate(Guid id)

{var template = _CustomerServiceContext.MessatgeTemplate.FirstOrDefault(p => p.Id ==id);if (template != null)

{

_CustomerServiceContext.MessatgeTemplate.Remove(template);

_CustomerServiceContext.SaveChanges();

}

}///

///批量設置是否可用///

///

///

public void BatchEnableTemplate(List ids, boolenabled)

{//TODO set enabled

}

}

第三步、創建webapi項目,并在其中建立對應的實體類,以及數據庫訪問類

須引入Microsoft.EntityFrameworkCore和Microsoft.EntityFrameworkCore.Design.

1、在appsettings.json中配置數據連接

"ConnectionStrings": {"CumstomerServiceConnection": "server=localhost;port=3306;database=CustomerServiceCenter;uid=root;pwd=root23456;CharSet=utf8"}

2、修改startup.cs類的ConfigureServices注入db訪問類

services.AddDbContext(p => p.UseMySql(Configuration.GetConnectionString("CumstomerServiceConnection")));

3、設置該webapi項目為啟動項目,在nuget程序包控制臺選擇第一步中創建的實體類項目依次運行如下腳本創建數據庫

1)add-migration init

2) update-database

上面的兩個命令中,add-migration表示添加數據遷移,其實就是將實體變更轉換成sql(add-migraion后面的init只是個名稱,可以自行定義),update-database是將生成的數據遷移信息更新到數據庫

另外一些可能用到的命令

remove-migration? ---將最近生成的遷移(沒有更新到數據庫的)移除掉

script-migration --生成數據庫遷移相應的腳本

------------------------

命令執行成功后,就可以在數據庫中找到創建好的數據庫和表了

821f97680989b87686b103b3486a9a30.png

script-datatable可以生成數據庫腳本語句

a26f74de4085f123a4daeb05bdcc8f15.png

好了,以上就完成了codefirst的簡單操作了。不過跟著第二步的業務類其實沒啥關系!!!如果只是進行數據遷移確實沒有service層什么事,但是業務邏輯要走通,實現crud,業務層還是必須的。

---------------------------------------------------------------------------------------------------------------------

以下就順帶寫下controller中引入service,實現簡單的刪除業務邏輯(其它的業務邏輯---略)

在webapi創建MessageTemplateController

[Route("api/[controller]")]

[ApiController]public classMessageTemplateController : ControllerBase

{privateMessageTemplateService _MessageTemplateService;publicMessageTemplateController(MessageTemplateService messageTemplateService)

{this._MessageTemplateService =messageTemplateService;

}///

///刪除///

///

[HttpPost("DeleteMessageTemplate")]public voidDeleteMessageTemplate(Guid id)

{

_MessageTemplateService.DeleteMessageTemplate(id);

}//TODO其他操作:查詢,新增,修改等

}

修改Startup.cs類,注入服務

public voidConfigureServices(IServiceCollection services)

{

services.AddControllers();

services.AddDbContext(p => p.UseMySql(Configuration.GetConnectionString("CumstomerServiceConnection")));#region 注入業務服務Assembly assembly= Assembly.Load("Qingy.DotNetCoreStudy.CustomerServiceService");

List types = assembly.GetTypes().Where(u => u.IsClass && !u.IsAbstract && !u.IsGenericType&& u.GetInterfaces().Any(p => p == typeof(ICustomerServicerSerice))

).ToList();foreach (var item intypes)

{

services.AddTransient(item);

}#endregion}

綜合以上,就可以將api到db的完整實現了。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392573.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392573.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392573.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode 34. 在排序數組中查找元素的第一個和最后一個位置(二分查找)

給定一個按照升序排列的整數數組 nums,和一個目標值 target。找出給定目標值在數組中的開始位置和結束位置。 如果數組中不存在目標值 target,返回 [-1, -1]。 進階: 你可以設計并實現時間復雜度為 O(log n) 的算法解決此問題嗎&#xff1…

CentOS6.7上使用FPM打包制作自己的rpm包

自定義rpm包,還是有逼格和實際生產環境的意義的。 (下面的文檔有的代碼由于博客排版的問題導致擠在了一起,需要自己判別) 安裝FPM fpm是ruby寫的,因此系統環境需要ruby,且ruby版本號大于1.8.5。 # 安裝ruby模塊 yum -y…

漢堡菜單_開發人員在編寫漢堡菜單時犯的錯誤

漢堡菜單by Jared Tong湯杰(Jared Tong) 開發人員在編寫漢堡菜單時犯的錯誤 (The mistake developers make when coding a hamburger menu) What do The New York Times’ developers get wrong about the hamburger menu, and what do Disney’s and Wikipedia’s get right?…

android 漲潮動畫加載_Android附帶漲潮動畫效果的曲線報表繪制

寫在前面本文屬于部分原創,實現安卓平臺正弦曲線類報表繪制功能介紹,基于網絡已有的曲線報表繪制類(LineGraphicView)自己添加了漲潮的漸變動畫算法最終效果圖廢話少說,直接上源碼一、自定義View LineGraphicView,本類注釋不算多&…

使用css3屬性transition實現頁面滾動

<!DOCTYPE html> <html><head><meta http-equiv"Content-type" content"text/html; charsetutf-8" /><title>慕課七夕主題</title><script src"http://libs.baidu.com/jquery/1.9.1/jquery.min.js">&…

leetcode 321. 拼接最大數(單調棧)

給定長度分別為 m 和 n 的兩個數組&#xff0c;其元素由 0-9 構成&#xff0c;表示兩個自然數各位上的數字。現在從這兩個數組中選出 k (k < m n) 個數字拼接成一個新的數&#xff0c;要求從同一個數組中取出的數字保持其在原數組中的相對順序。 求滿足該條件的最大數。結…

Oracle Study之--Oracle等待事件(5)

Db file single write這個等待事件通常只發生在一種情況下&#xff0c;就是Oracle 更新數據文件頭信息時&#xff08;比如發生Checkpoint&#xff09;。當這個等待事件很明顯時&#xff0c;需要考慮是不是數據庫中的數據文件數量太大&#xff0c;導致Oracle 需要花較長的時間來…

兩臺centos之間免密傳輸 scp

兩臺linux服務器之間免密scp&#xff0c;在A機器上向B遠程拷貝文件 操作步驟&#xff1a;1、在A機器上&#xff0c;執行ssh-keygen -t rsa&#xff0c;一路按Enter&#xff0c;不需要輸入任何內容。&#xff08;如有提示是否覆蓋&#xff0c;可輸入y后按回車&#xff09;2、到/…

jsp導出數據時離開頁面_您應該在要離開的公司開始使用數據

jsp導出數據時離開頁面If you’re new in data science, “doing data science” likely sounds like a big deal to you. You might think that you need meticulously collected data, all the tools for data science and a flawless knowledge before you can claim that y…

分步表單如何實現 html_HTML表格入門的分步指南

分步表單如何實現 htmlby Abhishek Jakhar通過阿比舍克賈卡(Abhishek Jakhar) HTML表格入門的分步指南 (A step-by-step guide to getting started with HTML tables) 總覽 (Overview) The web is filled with information like football scores, cricket scores, lists of em…

laravel mysql pdo,更改Laravel中的基本PDO配置

My shared web host have some problems with query prepares and I want to enable PDOs emulated prepares, theres no option for this in the config\database.php.Is there any way I can do that in Laravel?解決方案You can add an "options" array to add o…

Java多線程-工具篇-BlockingQueue

Java多線程-工具篇-BlockingQueue 轉載 http://www.cnblogs.com/jackyuj/archive/2010/11/24/1886553.html 這也是我們在多線程環境下&#xff0c;為什么需要BlockingQueue的原因。作為BlockingQueue的使用者&#xff0c;我們再也不需要關心什么時候需要阻塞線程&#xff0c;什…

leetcode 204. 計數質數

統計所有小于非負整數 n 的質數的數量。 示例 1&#xff1a; 輸入&#xff1a;n 10 輸出&#xff1a;4 解釋&#xff1a;小于 10 的質數一共有 4 個, 它們是 2, 3, 5, 7 。 解題思路 大于等于5的質數一定和6的倍數相鄰。例如5和7&#xff0c;11和13,17和19等等&#xff1b…

JAVA 網絡編程小記

在進行JAVA網絡編程時&#xff0c;發現寫入的數據對方等200ms左右才會收到。起初認為是JAVA自已進行了 Cache。進行flush也沒有效果。查看JDK代碼&#xff0c;Write操作直接調用的native方法&#xff0c;說明JAVA層面并沒有緩存。再看flush&#xff0c;只是一個空方法. FileOut…

vue生成靜態js文件_如何立即使用Vue.js生成靜態網站

vue生成靜態js文件by Ond?ej Polesn通過Ond?ejPolesn 如何立即使用Vue.js生成靜態網站 (How to generate a static website with Vue.js in no time) You have decided to build a static site, but where do you start? How do you select the right tool for the job wit…

查看文件夾大小的4種方法,總有一種是你喜歡的

有必要檢查文件夾的大小,以確定它們是否占用了太多的存儲空間。此外,如果你通過互聯網或其他存儲設備傳輸文件夾,還需要查看文件夾大小。 幸運的是,在Windows設備上查看文件夾大小非常容易。窗口中提供了圖形化和基于命令行的應用程序,為你提供了多種方法。 如何在Windo…

Python 獲取服務器的CPU個數

在使用gunicorn時&#xff0c;需要設置workers&#xff0c; 例如&#xff1a; gunicorn --workers3 app:app -b 0.0.0.0:9000 其中&#xff0c;worker的數量并不是越多越好&#xff0c;推薦值是CPU的個數x21&#xff0c; CPU個數使用如下的方式獲取&#xff1a; python -c impo…

多種數據庫連接工具_20多種熱門數據工具及其不具備的功能

多種數據庫連接工具In the past few months, the data ecosystem has continued to burgeon as some parts of the stack consolidate and as new challenges arise. Our first attempt to help stakeholders navigate this ecosystem highlighted 25 Hot New Data Tools and W…

怎么連接 mysql_怎樣連接連接數據庫

這個博客是為了說明怎么連接數據庫第一步&#xff1a;肯定是要下載數據庫&#xff0c;本人用的SqlServer2008&#xff0c;是從別人的U盤中拷來的。第二步&#xff1a;數據庫的登錄方式設置為混合登錄&#xff0c;步驟如下&#xff1a;1.打開數據庫這是數據庫界面&#xff0c;要…

webstorm環境安裝配置(less+autoprefixer)

node安裝&#xff1a; 參考地址&#xff1a;http://www.runoob.com/nodejs/nodejs-install-setup.html 1.下載node安裝包并完成安裝 2.在開始菜單打開node 3.查看是否安裝完成&#xff08;npm是node自帶安裝的&#xff09; 命令&#xff1a;node -v npm -v less安裝&#xff1a…