惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
V
Vulnerabilities – Threatpost
Google Online Security Blog
Google Online Security Blog
Hugging Face - Blog
Hugging Face - Blog
L
LINUX DO - 热门话题
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
D
Docker
C
Cyber Attacks, Cyber Crime and Cyber Security
MyScale Blog
MyScale Blog
P
Palo Alto Networks Blog
T
Tenable Blog
P
Privacy International News Feed
Google DeepMind News
Google DeepMind News
小众软件
小众软件
Cisco Talos Blog
Cisco Talos Blog
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cisco Blogs
T
Threat Research - Cisco Blogs
NISL@THU
NISL@THU
The Hacker News
The Hacker News
Project Zero
Project Zero
AWS News Blog
AWS News Blog
Simon Willison's Weblog
Simon Willison's Weblog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threatpost
V
Visual Studio Blog
The GitHub Blog
The GitHub Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
Jina AI
Jina AI
Cyberwarzone
Cyberwarzone
The Register - Security
The Register - Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
Vercel News
Vercel News
D
Darknet – Hacking Tools, Hacker News & Cyber Security
MongoDB | Blog
MongoDB | Blog
U
Unit 42
Scott Helme
Scott Helme
A
About on SuperTechFans
WordPress大学
WordPress大学
F
Fortinet All Blogs
大猫的无限游戏
大猫的无限游戏
G
GRAHAM CLULEY
Latest news
Latest news
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Schneier on Security

博客园 - sunwugang

026.数据库Sqlserver解决远程连接问题 C# DataTableToList 批处理自动删除指定文件夹中的文件夹以及文件 C# 开机自启动批处理bat文件 C# 将exe可执行程序设置为开机自启动 025.数据库下载&win10安装注意事项 024 数据库信息查询 + 连接串配置 C# Json操作 C# TextBox 新增文本并定位光标 C# base64转pdf + 上传至指定url C# 猜字谜 C# 闲来笔记 StringHelper--字符串左右添加指定字符 Vue学习笔记72--element ui Vue学习笔记71--histroy模式+hash模式 Vue学习笔记70--全局前置-路由守卫 + 后置路由守卫 + 独享守卫 + 组件内守卫 Vue学习笔记69--activated + deactivated Vue学习笔记68--缓存路由组件 Vue学习笔记67--编程式路由导航
C# SqlSuger
sunwugang · 2025-04-18 · via 博客园 - sunwugang
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace Demos.Helper
{
    public class SqlSugarHelper
    {
        private readonly SqlSugarClient _db;

        public SqlSugarHelper(string connectionString)
        {
            _db = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = connectionString,
                DbType = DbType.SqlServer, // 根据实际数据库类型修改
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
        }

        /// <summary>
        /// 事务处理多条执行语句
        /// </summary>
        /// <param name="action">事务操作委托</param>
        /// <returns>事务是否执行成功</returns>
        public bool UseTransaction(Action action)
        {
            try
            {
                _db.Ado.BeginTran();
                action();
                _db.Ado.CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                _db.Ado.RollbackTran();
                Console.WriteLine($"事务执行出错: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 插入单条记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entity">实体对象</param>
        /// <returns>插入是否成功</returns>
        public bool Insert<T>(T entity) where T : class, new()
        {
            // 开启 IDENTITY_INSERT
            //_db.Ado.ExecuteCommand("SET IDENTITY_INSERT Test ON");
            return _db.Insertable(entity).ExecuteCommand() > 0;
              // 关闭 IDENTITY_INSERT
            //db.Ado.ExecuteCommand("SET IDENTITY_INSERT Test OFF");
        }

        /// <summary>
        /// 插入多条记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entities">实体对象集合</param>
        /// <returns>插入成功的记录数</returns>
        public int InsertRange<T>(List<T> entities) where T : class, new()
        {
            return _db.Insertable(entities).ExecuteCommand();
        }

        /// <summary>
        /// 根据主键删除记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="id">主键值</param>
        /// <returns>删除是否成功</returns>
        public bool DeleteById<T>(object id) where T : class, new()
        {
            return _db.Deleteable<T>(id).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 根据条件删除记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>删除成功的记录数</returns>
        public int Delete<T>(Expression<Func<T, bool>> whereExpression) where T : class, new()
        {
            return _db.Deleteable<T>().Where(whereExpression).ExecuteCommand();
        }

        /// <summary>
        /// 更新单条记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entity">实体对象</param>
        /// <returns>更新是否成功</returns>
        public bool Update<T>(T entity) where T : class, new()
        {
            return _db.Updateable(entity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 根据条件更新记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="columns">要更新的列表达式</param>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>更新成功的记录数</returns>
        public int Update<T>(Expression<Func<T, T>> columns, Expression<Func<T, bool>> whereExpression)
            where T : class, new()
        {
            return _db.Updateable<T>().SetColumns(columns).Where(whereExpression).ExecuteCommand();
        }

        /// <summary>
        /// 根据主键查询单条记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="id">主键值</param>
        /// <returns>实体对象</returns>
        public T GetById<T>(object id) where T : class, new()
        {
            return _db.Queryable<T>().InSingle(id);
        }

        /// <summary>
        /// 根据条件查询单条记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>实体对象</returns>
        public T GetSingle<T>(Expression<Func<T, bool>> whereExpression) where T : class, new()
        {
            return _db.Queryable<T>().Single(whereExpression);
        }

        /// <summary>
        /// 根据条件查询多条记录
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>实体对象集合</returns>
        public List<T> GetList<T>(Expression<Func<T, bool>> whereExpression) where T : class, new()
        {
            return _db.Queryable<T>().Where(whereExpression).ToList();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="totalCount">总记录数</param>
        /// <returns>实体对象集合</returns>
        public List<T> GetPageList<T>(int pageIndex, int pageSize,
            Expression<Func<T, bool>> whereExpression, ref int totalCount) where T : class, new()
        {
            return _db.Queryable<T>().Where(whereExpression).ToPageList(pageIndex, pageSize, ref totalCount);
        }
    }

    //class Program
    //{
    //    static void Main()
    //    {
    //        string connectionString = "YourConnectionString";
    //        SqlSugarHelper helper = new SqlSugarHelper(connectionString);

    //        // 示例插入操作
    //        var entity = new YourEntity { /* 初始化属性 */ };
    //        bool insertResult = helper.Insert(entity);

    //        // 示例查询操作
    //        var list = helper.GetList<YourEntity>(x => x.SomeProperty == "SomeValue");
    //    }
    //}


    //class Program
    //{
    //    static void Main()
    //    {
    //        string connectionString = "YourConnectionString";
    //        SqlSugarHelper helper = new SqlSugarHelper(connectionString);

    //        bool transactionResult = helper.UseTransaction(() =>
    //        {
    //            // 示例插入操作
    //            var entity1 = new YourEntity { /* 初始化属性 */ };
    //            helper.Insert(entity1);

    //            // 示例更新操作
    //            var entity2 = helper.GetById<YourEntity>(1);
    //            if (entity2 != null)
    //            {
    //                // 修改实体属性
    //                helper.Update(entity2);
    //            }
    //        });

    //        if (transactionResult)
    //        {
    //            Console.WriteLine("事务执行成功");
    //        }
    //        else
    //        {
    //            Console.WriteLine("事务执行失败");
    //        }
    //    }
    //}


}





//// 定义要更新的列表达式
//Expression<Func<YourEntity, YourEntity>> columns = entity => new YourEntity
//{
//    Name = "UpdatedName",
//    Age = 25
//};

//// 动态构建条件表达式
//var parameter = Expression.Parameter(typeof(YourEntity), "entity");

//// 第一个条件:Age < 20
//var ageCondition = Expression.LessThan(Expression.Property(parameter, "Age"), Expression.Constant(20));

//// 第二个条件:City == "New York"
//var cityCondition = Expression.Equal(Expression.Property(parameter, "City"), Expression.Constant("New York"));

//// 组合条件,这里使用逻辑与(&&)
//var combinedCondition = Expression.AndAlso(ageCondition, cityCondition);

//// 构建最终的 Lambda 表达式
//var whereExpression = Expression.Lambda<Func<YourEntity, bool>>(combinedCondition, parameter);

//// 调用 Update 方法
//int updatedCount = helper.Update(columns, whereExpression);

//if (updatedCount > 0)
//{
//    Console.WriteLine($"成功更新 {updatedCount} 条记录。");
//}
//else
//{
//    Console.WriteLine("没有记录被更新。");
//}

调用示例

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demos.Model
{
    public class Test
    {
        /// <summary>
        /// Desc:- 
        /// Default:- 
        /// Nullable:False 
        /// </summary>
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int id { get; set; }

        /// <summary>
        /// Desc:- 
        /// Default:- 
        /// Nullable:True 
        /// </summary>
        public string name { get; set; }

        /// <summary>
        /// Desc:- 
        /// Default:- 
        /// Nullable:True 
        /// </summary>
        public string nickname { get; set; }

        /// <summary>
        /// Desc:- 
        /// Default:- 
        /// Nullable:True 
        /// </summary>
        public string age { get; set; }

    }
}
using Demos.Helper;
using Demos.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Demos
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Control.CheckForIllegalCrossThreadCalls = false;
        }
        string connStr = ConfigurationManager.AppSettings["connStr"].ToString();

        private void Form1_Load(object sender, EventArgs e)
        {
            SqlSugarHelper helper = new SqlSugarHelper(connStr);
            // 示例查询操作
            List<Test> list = helper.GetList<Test>(x => x.age == x.age);
            StringBuilder value = new StringBuilder();
            foreach (var item in list)
            {
                value.AppendLine(item.id + "," + item.name + "," + item.nickname + "," + item.age);
            }
            this.txtValue.Text = value.ToString();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Test test = new Test();
            //test.id = 4;
            test.name = "测试 name";
            test.nickname = "测试 nickname";
            test.age = "18";
            SqlSugarHelper helper = new SqlSugarHelper(connStr);
            bool insertResult = helper.Insert(test);
            this.btnQuery.PerformClick();
            MessageBox.Show("添加==>" + insertResult);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlSugarHelper helper = new SqlSugarHelper(connStr);
            int insertResult = helper.Delete<Test>(o=>o.id== 4);
            this.btnQuery.PerformClick();
            MessageBox.Show("删除==>" + insertResult);
        }
        private void btndelbyid_Click(object sender, EventArgs e)
        {
            Test test = new Test();
            test.name = "测试 name";
            test.nickname = "测试 nickname";
            test.age = "20";
            SqlSugarHelper helper = new SqlSugarHelper(connStr);
            var insertResult = helper.DeleteById<Test>(1);
            this.btnQuery.PerformClick();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            // 定义要更新的列表达式
            Expression<Func<Test, Test>> columns = entity => new Test
            {
                name = "UpdatedName",
                age = "19"
            };
            // 定义更新条件表达式
            Expression<Func<Test, bool>> whereExpression = entity => entity.id == 4;
            
            SqlSugarHelper helper = new SqlSugarHelper(connStr);
            int insertResult = helper.Update(columns, whereExpression);
            this.btnQuery.PerformClick();
            MessageBox.Show("修改==>" + insertResult);
        }

        private void btnUpdate2_Click(object sender, EventArgs e)
        {
            SqlSugarHelper helper = new SqlSugarHelper(connStr);
            //Test test = new Test();
            //test.id = 4;
            //test.name = "测试 name";
            //test.nickname = "测试 nickname";
            //test.age = "20";
            Test aa=  helper.GetById<Test>(4);
            aa.name = "110";
            //aa.id = 4;
            var bb = helper.Update(aa);
            this.btnQuery.PerformClick();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            SqlSugarHelper helper = new SqlSugarHelper(connStr);
            // 示例查询操作
            List<Test> list = helper.GetList<Test>(x => x.age == x.age);
            StringBuilder value = new StringBuilder();
            foreach (var item in list)
            {
                value.AppendLine(item.id + "," + item.name + "," + item.nickname + "," + item.age);
            }
            this.txtValue.Text = value.ToString();
        }

       
    }
}

App.config

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3     <startup> 
 4         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
 5     </startup>
 6     <appSettings>
 7         <!--数据库连接-->
 8         <add key="connStr" value="server=.;uid=sa;pwd=123456;database=SYPT_DB" />
 9 
10     </appSettings>
11   <runtime>
12     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
13       <dependentAssembly>
14         <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
15         <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
16       </dependentAssembly>
17     </assemblyBinding>
18   </runtime>
19 </configuration>