.NET6.0 API仓储+工作单元
配置数据库
-
引入依赖包
不同的数据库引入不同:-
公共依赖包:
Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Design Microsoft.EntityFrameworkCore.Tools
-
SqlServer:
Microsoft.EntityFrameworkCore.SqlServer
-
Sqlite:
Microsoft.EntityFrameworkCore.Sqlite
-
MySql:
Pomelo.EntityFrameworkCore.MySql
-
-
配置连接字符串
appsettings.json在这里插入代码片
文件中加如下代码
{
"ConnectionStrings": {
//sqlite
"ToDoConnection": "Data Source=to.db"
//sqlserver
"StudentDBConnection": "server=SKY-20161118TNS\\MYSQL2012;Initial Catalog=StudentDB;User ID=sa;Password=123456"
//mysql
"DBConnection": "Server=195.168.1.21;Port=3306;Database=amicauniqidserver;Uid=root;Pwd=123456;"
},
//mysql同时需要配置版本号
"Custom": {
"mysqlVer": "8.0.28-mysql"
}
}
Program.cs代码配置
// 配置数据库,sqlite数据库
builder.Services.AddDbContext<MyToDoContext>(option =>
{
var connectionStr = builder.Configuration.GetConnectionString("ToDoConnection");
option.UseSqlite(connectionStr, b =>
{
b.MigrationsAssembly("MyToDoApi");
});
})
//配置数据库,sqlserver连接池
//加载sqlserver,采用数据库连接池
var connectionStr = builder.Configuration.GetConnectionString("ToDoConnection");
builder.services.AddDbContextPool<AppDbContext>(option =>
{
option.UseSqlServer(connectionStr);
})
//配置数据库,mysql工厂
//加载mysql,采用数据库连接工厂
var connection = host.Configuration.GetConnectionString("DBConnection");
//获取自定义配置参数(mysql版本号)
Config custom = host.Configuration.GetSection("Custom").Get<Config>();
services.AddDbContextFactory<AppDbContext>(
optionsAction: options => options.UseMySql(connection, new MySqlServerVersion(custom.mysqlVer))
);
配置工作单元
- 引入依赖包
Microsoft.EntityFrameworkCore.UnitOfWork - 自定义Context类
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public MyDbContext (DbContextOptions<MyDbContext> optios) : base(optios)
{
}
//以下为数据库表映射实体类的集合
public DbSet<UserDto> UserDtos {
get; set; }
public