这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战
SqlSugar是一款 .NET 开源ORM框架,由果糖大数据科技团队维护和更新 www.donet5.com/Home/Doc
1、打开Nuget
点击项目引用 右键 Nuget管理,打开Nuget管理界面。
2、 添加Nuget引用
在搜索框里面输入SqlSugar,然后进行检索,在检索出来的结果里面选择我们需要的引用,这里有sqlsugar和sqlsugar core。一个是老版本的.net framework,一个是新框架.net core,或者现在叫.net。
点击列表可以在右侧看到框架的说明和依赖等信息。
3、配置数据库连接
我们可以使用 SqlSugarClient 或者 SqlSugarScope 对数据库进行增、删、查、改等功能
//创建数据库对象 SqlSugarClient
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "Server=.xxxxx",//连接符字串
DbType = DbType.SqlServer, //数据库类型
IsAutoCloseConnection = true //不设成true要手动close
});
//创建数据库对象 SqlSugarScope 用法小有区别
static SqlSugarScope scope= new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = "Server=.xxxxx",//连接符字串
DbType = DbType.SqlServer,//数据库类型
IsAutoCloseConnection = true //不设成true要手动close
},
db=> {
//(A)这里配置参数:所有上下文都生效
// db.Aop.xxx=xxxx..
});
//(B)这里设置参数:当前上下文有效
//scope.Aop.xxx=xxxx..
Task.Run(()=>{
scope.Queryable<T>().ToList();//这新开一个上下文B处的配置将失效,A处配置有效
});
//这里A和B处的配置都有效
//创建数据库对象 SqlSugarClient
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "Server=.xxxxx",//连接符字串
DbType = DbType.SqlServer, //数据库类型
IsAutoCloseConnection = true //不设成true要手动close
});
//创建数据库对象 SqlSugarScope 用法小有区别
static SqlSugarScope scope= new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = "Server=.xxxxx",//连接符字串
DbType = DbType.SqlServer,//数据库类型
IsAutoCloseConnection = true //不设成true要手动close
},
db=> {
//(A)这里配置参数:所有上下文都生效
// db.Aop.xxx=xxxx..
});
//(B)这里设置参数:当前上下文有效
//scope.Aop.xxx=xxxx..
Task.Run(()=>{
scope.Queryable<T>().ToList();//这新开一个上下文B处的配置将失效,A处配置有效
});
//这里A和B处的配置都有效
这样我们就可以直接使用SqlSugarClient来进行数据库操作了。但是对于ORM来说最好生成实体,并且用service层来操作更方便。
4、生成实体
生成实体我们可以使用SqlSugarClient 的DbFirst 直接生成实体。
db.DbFirst.IsCreateAttribute().CreateClassFile(@"F:\Project\Model", "Project.Model");
这样我们的实体就生成好了。我们可以使用仓储的方式构建service层。
5、创建仓储
定义的Repository是公用类,不包含具体的类务逻辑,有自带的基本方法,其它实体对应的service 直接继承,额外的扩展方法自己写。
public class Repository<T> : SimpleClient<T> where T : class, new()
{
public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
{
base.Context=context;//ioc注入的对象
// base.Context=DbScoped.SugarScope; SqlSugar.Ioc这样写
// base.Context=DbHelper.GetDbInstance()当然也可以手动去赋值
}
/// <summary>
/// 扩展方法,自带方法不能满足的时候可以添加新方法
/// </summary>
/// <returns></returns>
public List<T> CommQuery(string json)
{
//base.Context.Queryable<T>().ToList();可以拿到SqlSugarClient 做复杂操作
return null;
}
}
6、使用仓储
//举例 Example 实体
public class ExampleService: Repository<Example>
{
//业务方法
public Example GetExample(int id)
{
return base.GetById(it);
}
}