一、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();
}
publicclass AppDbContext :DbContext
{
public DbSet
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";
【C#学习笔记|NetCore实现DbContext接口设计】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#期末复习编程题(老师猜的)
- linux|MySQL数据库增删改查(基础操作命令详解)
- mysql优化|MySQL到底怎么优化?
- java|Java-Mybatis(四): 动态SQL、标签、缓存
- sql|Mybatis-----动态SQL 狂神
- MyBatis|Mybatis基本使用总括(单表/多表/动态sql)
- mybatis|mybatis中的动态sql语句和多表查询
- mysql|SQL(面试实战05)
- MySQL|MySQL的JDBC编程及增删改查