zoukankan      html  css  js  c++  java
  • .NET Core中使用EF Core连接MySQL

    最近一直在捣鼓.NET Core方面的东西,顺便写下点东西记录下

    1、打开vs2017,新建一个项目

    2、vs会自动生成一个项目,然后打开NuGet搜索MySql.Data.EntityFrameworkCore下载

    3、然后在Models下面新建一个Student类,然后再新建一个类继承DbContext类

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace MySql.Test.Models
    {
        public class Student
        {
            [Key]
            public int ID { get; set; }
            [Display(Name="姓名")]
            public string Name { get; set; }
            [Display(Name="年龄")]
            public int Age { get; set; }
        }
    }
    public class MysqlDbContext : DbContext
        {
            public MysqlDbContext(DbContextOptions<MysqlDbContext> options):base(options)
            {
    
            }
            //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            //{
            //    optionsBuilder.UseMySQL("server=.;database=TestDb;user=root;password=123456;");
            //}
            //protected override void OnModelCreating(ModelBuilder modelBuilder)
            //{
            //    base.OnModelCreating(modelBuilder);
            //}
    
            public DbSet<Student> students { get; set; }
        }

    这里说明下MySQL连接也可以写在这里,但我们后面会注入到services中

    4、然后我们在appsettings.json里添加一个连接字符串(.NET Core使用在appsettings.json里读取配置,类似于webconfig)

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": { "MysqlConnection": "Data Source=.;Database=TestDb;User ID=root;Password=123456;pooling=true;port=3306;sslmode=none;CharSet=utf8;" }
    }

    5、然后打开Startup,将MySQL连接注入services,具体Startup使用可以去看相关博客

    public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
                var connection = Configuration.GetConnectionString("MysqlConnection");
                services.AddDbContext<MysqlDbContext>(options => options.UseMySQL(connection));
            }

    6、然后我们就可以开始数据迁移了

    在vs中的“程序包管理器控制台”中输入如下两个命令

    Add-Migration init(执行此命令项目生成一个目录(Migration))
    Update-Database init

    然后我们就可以在数据库看到生成的数据库以及数据表了

    注意:如果出现错误提示xxxx.__EFMigrationsHistory  doesn't exist

    我们需要手动在数据库创建__EFMigrationsHistory这张表

    然后再开始迁移就好了

    最后还遇到一个问题是:如果已经数据迁移后,又在Models添加一个类再次更新时需要指定到具体的表名,不然会提示原来的表已经存在,或者删除原来的数据表(不推荐)。

  • 相关阅读:
    python ddt 传多个参数值示例
    Appium 输入 & 符号,实际输入&-
    curl 调用jenkins的api
    Android WebView的Js对象注入漏洞解决方案
    Could not find com.android.tools.build:gradle:1.3.0.
    react-native疑难
    win上搭建react-native android环境
    gradle大体内容
    android studio This client is too old to work with the working copy at
    sharedPreference
  • 原文地址:https://www.cnblogs.com/lyps/p/9916167.html
Copyright © 2011-2022 走看看