.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;           

        }

 

posted @   James·wang  阅读(1264)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-01-24 【转】SQL2008的sa账户被禁用,其他账户无法连接的解决方法
点击右上角即可分享
微信分享提示