.Net Core +MVC+EF+MySQL(Code First)(二)

1.打开vs2017,文件》新建》项目,选择Asp.Net Core Web应用程序,项目名为Test,模板选.net core2.0

2.项目的根目录新建Models文件夹和Controllers文件夹和Views文件夹

3.Models文件夹下建一个User类

  public class User
  {
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
  }

4.继续在Models文件夹下新建一个数据库对象类DataContext类

  ps:需要引用using Microsoft.EntityFrameworkCore;
  public class DataContext:DbContext
  {
    public DataContext(DbContextOptions<DataContext> options):base(options)
    {
    }
    public DbSet<User> Users { get; set; }
  }

5.通过Nuget添加Pomelo.EntityFrameworkCore.MySql

  工具-》Nuget包管理器-》管理解决方案的Nuget包管理器

6.添加连接字符串,方法有两种

  第一种:直接在Startup.cs文件中...... 

      ps:需要引用using Microsoft.EntityFrameworkCore;
            using Test.Models;

      public void ConfigureServices(IServiceCollection services)
      {
        var connection = @"Data Source=.;Database=Zhangtiancai;User ID=root;Password=*;pooling=true;CharSet=utf8;port=3306;sslmode=none";
        services.AddDbContext<DataContext>(options => options.UseMySql(connection));
        services.AddMvc();
      }

  第二种:先在appsetting.json中添加节点......      

      "ConnectionStrings": {
          "MySqlConnection": "Data Source=.;Database=Zhangtiancai;User ID=root;Password=*;pooling=true;CharSet=utf8;port=3306;sslmode=none"
        }
      然后在Startup.cs修改如下代码......
      ps:需要引用using Microsoft.EntityFrameworkCore;
            using Test.Models;

      public void ConfigureServices(IServiceCollection services)
      {
            var connection = Configuration.GetConnectionString("MySqlConnection");
            services.AddDbContext<DataContext>(options => options.UseMySql(connection));
            services.AddMvc();
      }

7.接下来比较轻松的操作了,手动来生成数据库,与原来的mvc code first相比,不需要进行数据的增操作就可以生成数据库及其表。
 可能win7系统的话需要更新一下XShell,自行百度谷歌更新。
    工具-》Nuget包管理器-》程序包管理控制台

输入 Add-Migration MyFirstMigration  命令行

再输入 Update-Database  执行,Done表示已经在本地mysql成功生成。此时会发现项目多了一个文件夹,如下,

8.接下来进行MySQL数据库的增删改查操作
  在Controllers文件夹下新建一个控制器Index,并在此控制器下添加login页面,内容如下......

 

 

  9.修改默认页面路由规则,在app.UseMvc()中修改

10.运行项目

  https://localhost:44364/Index/login,查看mysql数据库(可借助navicat的可视化工具),如图......

  注意:若是远程连接虚拟机的MySQL数据库时,需要先把表里的root改为%,自行百度。否则连接失败

 

The End。

 


  

  
posted @ 2018-09-07 17:18  超级驼鹿  阅读(989)  评论(0编辑  收藏  举报
/*