依賴項:
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; }