感觉网上的方案都比较复杂,啃了半天微软的文档,总结了一个简单的方法。从IDbContextOptions入手,用简单的三层方法就可以实现。
一、App.Model
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace App.Model
{
[Table("tgoods")]
public class Goods
{
[Key]
public int rd { get; set; }
[Required]
public string id { get; set; }
public string name { get; set; }
}//end class
二、App.Service
using Microsoft.EntityFrameworkCore;
using System.Data.Common;
using System.Reflection;
using App.Model;
namespace App.Service
{
public interface IDbContextOptions
{
public DbContextOptions GetDbContextOptions();
}
public class AppDbContext :DbContext
{
public DbSet<Goods>? GoodsList { get; set; }
public AppDbContext(DbContextOptions options):base(options)
{
}
}
}
三、App.Service.MySql
using Microsoft.EntityFrameworkCore;
using App.Model;
using App.Service;
namespace App.Service.MySql
{
public class MySqlDbContextOptions :IDbContextOptions
{
public DbContextOptions GetDbContextOptions()
{
string sql = @"Server=localhost; Port=3306; Database=data; User=root; Password=root; CharSet=utf8; Allow User Variables=true;";
DbContextOptions _options = new DbContextOptionsBuilder().UseMySQL(sql).Options;
return _options;
}
}//end class
}
四、UI层实现
//下面的2句可以通过配置文件来读取,自由发挥哈。可以参考紧跟后面的注释语句
string? assemblyName = System.IO.Directory.GetCurrentDirectory() + @"\App.Service.MySql.dll";
string? className = @"App.Service.MySql.MySqlDbContextOptions";
//具体的配置文件读取可参考NetCore读取JSON配置文件_海阳宜家电脑的博客-优快云博客
// string? m_Provider = DBManager.GetProvider();
//string? m_Database = DBManager.GetDataBase();
//string? assemblyName = "DBUtilty.Service." + m_Database;
//string? className = assemblyName + "." + m_Database + "Helper";
Assembly assembly = Assembly.LoadFrom(assemblyName);
IDbContextOptions _options = (IDbContextOptions)assembly.CreateInstance(className);
if (_options is null) MessageBox.Show("_options is null");
myDb = new AppDbContext(_options.GetDbContextOptions());