NetCore实现DbContext接口设计

一、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? 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层实现

            string? assemblyName = System.IO.Directory.GetCurrentDirectory() + @"\App.Service.MySql.dll";
            string? className = @"App.Service.MySql.MySqlDbContextOptions";

            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());

你可能感兴趣的:(C#学习笔记,c#,mysql,netcore,dbcontext)