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即可

    Entityframework Core for Mysql on Mac 笔记_第1张图片


     
  • 建立一个简单的数据库,并为数据库添加一个Table,Table中的属性随意。我的数据库取名test_1,下面是我添加的表格:

Entityframework Core for Mysql on Mac 笔记_第2张图片

  •  新建一个基于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
  •  

    如果你在运行上述命令时报错:

Entityframework Core for Mysql on Mac 笔记_第3张图片

原因是dotnet ef tool 不再属于.net core SDK中的一部分。通过执行下面的命令,可以将dotnet ef变成一个全局可用的命令工具:

dotnet tool install --global dotnet-ef

执行成功后会在你的项目里面生成一个文件夹,包含有对应table的类文件,和一个数据库映射文件:

Entityframework Core for Mysql on Mac 笔记_第4张图片

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");
        }
    }
}

数据库里面查看结果:

Entityframework Core for Mysql on Mac 笔记_第5张图片

需要说明的是这里使用类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文件:

Entityframework Core for Mysql on Mac 笔记_第6张图片

将配置文件放到appSetting标签中:



    
        
    

这样利用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文件里面。

上面的项目代码链接:代码

你可能感兴趣的:(EF,core,数据库,mysql,c#)