0
点赞
收藏
分享

微信扫一扫

.Net Core 3.1 EF连接MySql数据库配置

琛彤麻麻 2022-03-30 阅读 63


依赖项:

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools
MySql.Data
MySql.EntityFrameworkCore
Microsoft.AspNetCore.Mvc

1、创建DbContext文件:

public class SqlDbContext: DbContext
{
//方式一:
//public SqlDbContext(DbContextOptions<SqlDbContext> options) : base(options) { } 

public SqlDbContext()
{
//如果要访问的数据库存在,则不做操作,如果不存在,会自动创建所有数据表和模式
Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
//方式二:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//SQL Server/Azure SQL 数据库、SQLite、Azure Cosmos DB、MySQL、PostgreSQL数据库连接
IConfiguration congifuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
string connStr = congifuration["ConnectionStrings:MySqlConnection"];
optionsBuilder.UseMySQL(connStr); //使用MySQL数据库
}

/// <summary>
/// sys
/// </summary>
public DbSet<Customer> Customer { get; set; }

}


2、配置“appsettings.json”文件:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": { "MySqlConnection": "Server=localhost;Database=DwDB;User ID=root;password=root;port=3306;sslmode=none;CharSet=utf8" }
}


3、配置“Startup.cs"文件(注意:我们重载了OnConfiguring,在这里不需要如下配置):

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
//使用MySQL数据库方式一使用
//services.AddDbContextPool<SqlDbContext>(options => options.UseMySQL(Configuration.GetConnectionString("MySqlConnection")));

//使用MSSQL数据库
// services.AddDbContext<SqlDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MSSqlConnection")));
}


3、使用方式如下:

private readonly SqlDbContext db = new SqlDbContext();
public List<Customer> GetList()
{
var aa= db.Customer.ToList();
return aa;

}




学习交流群:364976091


举报

相关推荐

0 条评论