NET Core 6 .0 配置 SqlSugar

发布时间 2023-08-25 20:21:10作者: 花开富贵-

 

选中项目NuGet包管理安装SqlSugarCore 

  安装好后>在配置文件中创建数据库连接字符串

创建一个SqlSugarContext

 

 

using RBACHS_Domain;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace RBACHS_IRepository
{
public class SqlSugarContext
{

public readonly ISqlSugarClient db;

public SqlSugarContext(ISqlSugarClient db )
{
this.db = db;
}


public void CreateTable()
{
db.DbMaintenance.CreateDatabase();//没有数据库则新建
db.CodeFirst.SetStringDefaultLength(50).BackupTable().InitTables(new Type[]
{
typeof(Aundit),
typeof(ClientInfo),
typeof(Dictionary),
typeof(District),
typeof(Menu),
typeof(Project),
typeof(Role),
typeof(RoleMenu),
typeof(Survey),
typeof(User),
typeof(UserRole),
});
}

}
}

 

 把需要迁移的视图 放到里面 然后在Program启动项里面 加入上下文

 

//注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
builder.Services.AddHttpContextAccessor();
//注册SqlSugar用AddScoped
builder.Services.AddScoped<ISqlSugarClient>(s =>
{
//Scoped用SqlSugarClient
SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
{
DbType = SqlSugar.DbType.MySql,
ConnectionString = builder.Configuration.GetConnectionString("MySqlHSFC"),
IsAutoCloseConnection = true,
},
db =>
{


});
return sqlSugar;
});

 

 

最后在接口里面 生成 创建 SqlSugarContext 的构造函数

 

 

最后写一个迁移方法

 

 

 最后返回hehe 就完成了