NetCore实现DbContext接口兼容不同的数据库

感觉网上的方案都比较复杂,啃了半天微软的文档,总结了一个简单的方法。从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());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值