本教程使用vs2017 + dotnet core2.0 + MySql5.7.19

 

1.打开vs2017,文件》新建》项目,选择Asp.Net Core Web应用程序

 

2.项目名称可以写Test,新建的模板选择.net core 2.0的Web应用程序。如下图:

DotNet Core 2.0使用MySql实现Code First

 

3.在项目根目录下新建一个Models文件夹。

 

4.在Models文件夹下新建一个User类。

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

 

5.在Models文件夹下新建一个DataContext类。

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

 

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

 

7.修改Startup.cs文件,用于Code First创建数据库。这里可以有两种方法,依次来说。

 

7.1直接将数据库连接字符串硬编码在Startup.cs文件中

//using Microsoft.EntityFrameworkCore;
//using Test.Models;

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-18
猜你喜欢
  • 2021-10-15
  • 2022-12-23
  • 2022-02-19
  • 2021-09-22
  • 2022-03-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案