时间:2021-07-01 10:21:17 帮助过:22人阅读
下面是SqlSugar生成的Sql,不难发现插入数组的sql非常的犀利,采用的是insert select 语法。
INSERT INTO [Users] ([UserName],[Email],[Address]) VALUES (@UserName,@Email,@Address) ; {"@UserName":"zara1","@Email":"sad","@Address":"asd"} INSERT [Users] ([UserName],[Email],[Address]) SELECT N‘zara1‘ AS [UserName],N‘sad‘ AS [Email],N‘asd‘ AS [Address] UNION ALL SELECT N‘zaranet‘ AS [UserName],N‘asd‘ AS [Email],N‘zxc‘ AS [Address]
在说一说更新和删除吧,当然他们同样有着range系列的操作,其代码所示:
View CodeSqlSugar的事务简单使用,我通常都是这么用的,通过这种方式是免去 db.CommitTran();这种啰嗦且邋遢代码。
var result = Db.Ado.UseTran(() => { var obj = UsersDb.GetById(0); obj.UserName = "事务demo"; UsersDb.Update(obj); }); if (result.IsSuccess) { Console.WriteLine("事务提交了"); //成功 } else { Console.WriteLine(result.ErrorMessage); }
UsersService.cs
public class UsersService: DbContext<User> { //有特殊需要的时候在重写方法组 }
DbContext中被改造成了泛型类,你传过来什么我干什么,这样DbContext真的就是管上下文的了,其优雅度从代码中就可以看出!如果你有特殊情况你需要重写方法,你直接重写即可,这个时候你就可以把这个东西想象成三层框架中的BLL.
public class UsersService : DbContext<Users> { public override List<Users> GetList() { return base.GetList(); } }
其DbContext的最终定义:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SqlSugar; namespace dapperDemo { public class DbContext<T> where T: class,new() { public DbContext() { Db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "Data Source=DESKTOP-OEJGKOO;Initial Catalog=TextInfo;Integrated Security=True", DbType = SqlSugar.DbType.SqlServer, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }); //调式代码 用来打印SQL Db.Aop.OnLogExecuting = (sql, pars) => { Console.WriteLine(sql + "\r\n" + Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); Console.WriteLine(); }; } public SqlSugarClient Db; public SimpleClient<Users> UsersDb { get { return new SimpleClient<Users>(Db); } } public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } } /// <summary> /// 可重写的更新 /// </summary> public virtual bool Update(T obj) { return CurrentDb.Update(obj); } public virtual bool Delete(dynamic id) { return CurrentDb.DeleteById(id); } public virtual List<T> GetList() { return CurrentDb.GetList(); } } }
喜欢的话,点个赞噢??。
【Zara原创】SqlSugar4轻量级ORM框架的使用指南
标签:OLE serve .exe system 示例 text 连接 重写 connect