.Net Core 3.1 EF连接MySql数据库配置
依赖项:
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; }
微信号:jamesworkshop 学习QQ群:364976091
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-01-24 【转】SQL2008的sa账户被禁用,其他账户无法连接的解决方法