SQL Sugar 的功能还是非常强大的,具体的不再赘述,见官方文档:SqlSugar ORM 5.X 官网 、文档、教程 - SqlSugar 5x - .NET果糖网
项目使用SqlSugar遇到的有些问题,在此记录一下。
刚开始在项目中Program.cs写的注入代码如下:
//注入数据库连接
builder.Services.AddScoped(db =>
{
return new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = builder.Configuration.GetConnectionString("ConnectString"),
DbType = DbType.MySql,
IsAutoCloseConnection = true,
});
});
结果程序运行的时候报错如下:
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: *BLL Lifetime: Scoped ImplementationType: *BLL': Unable to resolve service for type 'SqlSugar.ISqlSugarClient' while attempting to activate '*DAL'.)
然后开始查照各种帖子,找了好久都找不到问题导体出在哪,然后在一篇帖子中看到了,在注入时加入
builder.Services.AddScoped(db =>
{
return new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = builder.Configuration.GetConnectionString("ConnectString"),
DbType = DbType.MySql,
IsAutoCloseConnection = true,
});
});
我这里使用的是SqlSugarClient,如果使用的是Scop模式,声明的时候使用SqlSugarScope即可。
builder.Services.AddSingleton(db =>
{
return new SqlSugarScope(
new ConnectionConfig()
{
DbType = SqlSugar.DbType.SqlServer,
ConnectionString = builder.Configuration.GetConnectionString("ConnectString"),
IsAutoCloseConnection = true,
});
});
官方的注入方式如下,这种方式需要在WebApi中引入Nuget: SqlSugar.IOC,之后才能在progarm.cs中识别到AddSqlSugar()方法。
builder.Services.AddSqlSugar(new IocConfig()
{
ConnectionString = "server=.;uid=sa;pwd=haosql;database=SQLSUGAR4XTEST",
DbType = IocDbType.SqlServer,
IsAutoCloseConnection = true//自动释放
});
在DAL中使用时,可以直接通过构造函数注入的方式使用:
public class TestDAL //: IDisposable
{
public readonly ISqlSugarClient _dbClient;
public TestDAL(ISqlSugarClient dbClient)
{
_dbClient = dbClient;
}
//列表查询
public List List()
{
var query = _dbClient.Queryable().ToList();
return query;
}
}
示例中是简单的列表查询,其他的增删改等功能详见官方操作文档:基本查询 - SqlSugar 5x - .NET果糖网
参考文章连接:NET Core 6 .0 配置 SqlSugar_加点孜然.的博客-CSDN博客_services.getservice