Entityframework Core for Mysql on Mac 筆記

此文主要記錄自己使用EF core 在項目中適配Mysql數據庫,以便自己後續查找。

目錄

一. 準備工作

二.生產映射代碼

三.使用數據庫模型進行數據讀寫

四.將配置信息寫入配置文件



一. 準備工作

  • 首先在mac上安裝mysql數據庫,你可以選擇官網下載dmg文件,也可使用brew install Mysql命令安裝,安裝後可能還需要設置一下訪問路徑,相關文章很多,這裏不再贅述。
  • 爲了方便使用,建議也下載一個mac端的workbench,可視化界面。鏈接上mysql服務器,用戶名默認是root,本機地址是127.0.0.1,端口默認爲3306,密碼爲自己安裝時設定的密碼。需要注意的是,workbench默認不顯示自帶的數據庫,你需要設置一下:進入edit>preference>sql editor ,勾選show metadata and internal schemas即可


     
  • 建立一個簡單的數據庫,併爲數據庫添加一個Table,Table中的屬性隨意。我的數據庫取名test_1,下面是我添加的表格:

  •  新建一個基於dotnet core3.0+ 的控制檯程序,你可以使用mac版的visual studio,也可以使用dotnet命令,然後爲項目添加下面的庫:
  1. Microsoft.EntityFrameworkCore.Design

  2. Microsoft.EntityFrameworkCore.Tools

  3. MySql.Data.EntityFrameworkCore

  4. Mysql官網有詳細教程

二.生產映射代碼

在前面的準備工作完成後,打開命令終端,進入到你項目所在的目錄執行:

dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -o sakila -f

綠色的部分是數據庫的相關信息,默認生產的文件會放在“sakila”文件夾,你可以自行修改名字。如果你的數據庫有多個table,只想生成指定的table映射文件,可以在-f的前面加上你想要的table名字:

dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -o sakila -t actor -t film -t film_actor -t language -f
  •  

    如果你在運行上述命令時報錯:

原因是dotnet ef tool 不再屬於.net core SDK中的一部分。通過執行下面的命令,可以將dotnet ef變成一個全局可用的命令工具:

dotnet tool install --global dotnet-ef

執行成功後會在你的項目裏面生成一個文件夾,包含有對應table的類文件,和一個數據庫映射文件:

test1中NewTable就是對應的表格,test_1Context.cs對應的是數據庫對象模型類。

三.使用數據庫模型進行數據讀寫

添加一個新建類文件,我在前面截圖中爲TestModel.cs 。寫了一個添加和刪除的函數:

using System;
using MysqlEntityFramework.test1;

namespace MysqlEntityFramework
{
    public class TestModel
    {

        public static readonly test_1Context test_1Context = new test_1Context();

        public static void AddItem(object item)
        {
            try
            {
                test_1Context.Add(item);
                test_1Context.SaveChanges();
                Console.WriteLine("添加成功!");
            }
            catch(Exception e)
            {
                Console.WriteLine($"操作失敗!  {e.Message}");
            }
        }

        public static void DeleteItem(Type type, string id)
        {
            try
            {
                var ans = test_1Context.Find(type, id);
                test_1Context.Remove(ans);
                test_1Context.SaveChanges();
                Console.WriteLine("Operation Successed!");
            }
            catch(Exception e)
            {
                Console.WriteLine($"Operation failed! -------{e.Message}");
            }
        }
            
    }
}

考慮到一個數據庫可能有多個table,所以使用了泛型。在main函數添加一行數據:

using System;
using MysqlEntityFramework.test1;


namespace MysqlEntityFramework
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            NewTable new1 = new NewTable
            {
                Id = Guid.NewGuid().ToString(),
                Name = "Jim",
                Age = 13,
                Gender = 0,
                Hight = 137,
                Weight = 40,
                Time = DateTime.Now
            };
            TestModel.AddItem(new1);
            TestModel.DeleteItem(typeof(NewTable), "1");
        }
    }
}

數據庫裏面查看結果:

需要說明的是這裏使用類Guid(全局唯一標識符),可以生存一個64位的id,基本可以認爲不會生成同一個id,這樣任何時候都可以添加成功。

四.將配置信息寫入配置文件

在數據庫的映射文件中,會有這麼一個警告:

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseMySQL("server=localhost;port=3306;user=root;password=abcd1992qyl;database=test_1");
            }
        }

警告的原因是你的鏈接信息都暴露在了代碼之中。建議使用其它方式保存。一種比較簡單的方式是將它們放到你的配置文件中去。給你的項目添加一個config文件:

將配置文件放到appSetting標籤中:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="test_database"
             value="server=127.0.0.1;port=3306;user=root;password=abcd1992qyl;database=test_1"/>
    </appSettings>
</configuration>

這樣利用Configuration中的對象加載配置文件,讀取配置信息就可以實現我們想要的效果:

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string sVlaue = ConfigurationManager.AppSettings["test_database"];
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseMySQL(sVlaue);
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
               // optionsBuilder.UseMySQL("server=localhost;port=3306;user=root;password=abcd1992qyl;database=test_1");
            }
        }

當然你也可以寫一個json文件,放在json文件裏面。

上面的項目代碼鏈接:代碼

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