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

        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM