首页 > 数据库 >C# SqlSugar学习笔记

C# SqlSugar学习笔记

时间:2024-11-07 18:48:37浏览次数:7  
标签:C# System 笔记 Forms Windows new Drawing SqlSugar Size

前言

今天介绍一款C# ORM框架

什么是ORM?

来看一下百度术语:对象关系映射(英语:Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换

 通俗理解ORM

我们只需要知道ORM是一种技术,使用了ORM之后我们就不必在代码中写sql

常用的ORM框架

Mybatis:服务于Java开发

EF Core、Sqlsugar:服务于DotNet开发

Sqlsugar介绍

由果糖团队维护的一款开源DotNet ORM框架

官网地址:SqlSugar .Net ORM 5.X 官网 、文档、教程 - SqlSugar 5x - .NET果糖网 (donet5.com)

学习安排

官网的教程其实很详细,也在持续更新,新手可能入门的时候不知道怎么看教程

这里,我以一个简易的CRUD小项目为例,入门级讲解如何利用sqlsugar实现增删改查

后续我会结合实际工作中的项目开发更新学习笔记哈

备注:博客上一些人直接把官网内容原封不动照搬过来,也不知道咋想的,反正我当时入门的时候找了好多帖子,看都看不懂,学又学不废,可能都是大佬随手记的吧

这篇帖子我就以小白的视角讲解sqlsugar

新建winform桌面应用

添加基本布局

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonQuery_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAdd_Click(object sender, EventArgs e)
        {

        }
    }
}
namespace WindowsFormsApp3
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.textBoxName = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.textBoxAge = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.textBoxAddress = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.textBoxEmployeeNumber = new System.Windows.Forms.TextBox();
            this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
            this.label5 = new System.Windows.Forms.Label();
            this.buttonQuery = new System.Windows.Forms.Button();
            this.buttonAdd = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGridView1
            // 
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(33, 184);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.RowHeadersWidth = 82;
            this.dataGridView1.RowTemplate.Height = 37;
            this.dataGridView1.Size = new System.Drawing.Size(1532, 616);
            this.dataGridView1.TabIndex = 0;
            // 
            // textBoxName
            // 
            this.textBoxName.Location = new System.Drawing.Point(93, 32);
            this.textBoxName.Name = "textBoxName";
            this.textBoxName.Size = new System.Drawing.Size(156, 35);
            this.textBoxName.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(29, 37);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(58, 24);
            this.label1.TabIndex = 2;
            this.label1.Text = "姓名";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(275, 37);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(58, 24);
            this.label2.TabIndex = 4;
            this.label2.Text = "年龄";
            // 
            // textBoxAge
            // 
            this.textBoxAge.Location = new System.Drawing.Point(339, 32);
            this.textBoxAge.Name = "textBoxAge";
            this.textBoxAge.Size = new System.Drawing.Size(156, 35);
            this.textBoxAge.TabIndex = 3;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(822, 37);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(106, 24);
            this.label3.TabIndex = 6;
            this.label3.Text = "家庭住址";
            // 
            // textBoxAddress
            // 
            this.textBoxAddress.Location = new System.Drawing.Point(936, 32);
            this.textBoxAddress.Name = "textBoxAddress";
            this.textBoxAddress.Size = new System.Drawing.Size(382, 35);
            this.textBoxAddress.TabIndex = 5;
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(545, 37);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(58, 24);
            this.label4.TabIndex = 8;
            this.label4.Text = "工号";
            // 
            // textBoxEmployeeNumber
            // 
            this.textBoxEmployeeNumber.Location = new System.Drawing.Point(609, 32);
            this.textBoxEmployeeNumber.Name = "textBoxEmployeeNumber";
            this.textBoxEmployeeNumber.Size = new System.Drawing.Size(156, 35);
            this.textBoxEmployeeNumber.TabIndex = 7;
            // 
            // dateTimePicker1
            // 
            this.dateTimePicker1.Location = new System.Drawing.Point(1491, 32);
            this.dateTimePicker1.Name = "dateTimePicker1";
            this.dateTimePicker1.Size = new System.Drawing.Size(200, 35);
            this.dateTimePicker1.TabIndex = 9;
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(1360, 37);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(106, 24);
            this.label5.TabIndex = 10;
            this.label5.Text = "入职时间";
            // 
            // buttonQuery
            // 
            this.buttonQuery.Location = new System.Drawing.Point(33, 102);
            this.buttonQuery.Name = "buttonQuery";
            this.buttonQuery.Size = new System.Drawing.Size(79, 41);
            this.buttonQuery.TabIndex = 11;
            this.buttonQuery.Text = "查询";
            this.buttonQuery.UseVisualStyleBackColor = true;
            this.buttonQuery.Click += new System.EventHandler(this.buttonQuery_Click);
            // 
            // buttonAdd
            // 
            this.buttonAdd.Location = new System.Drawing.Point(147, 102);
            this.buttonAdd.Name = "buttonAdd";
            this.buttonAdd.Size = new System.Drawing.Size(79, 41);
            this.buttonAdd.TabIndex = 12;
            this.buttonAdd.Text = "新增";
            this.buttonAdd.UseVisualStyleBackColor = true;
            this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
            // 
            // Form1
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
            this.ClientSize = new System.Drawing.Size(1764, 845);
            this.Controls.Add(this.buttonAdd);
            this.Controls.Add(this.buttonQuery);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.dateTimePicker1);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.textBoxEmployeeNumber);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.textBoxAddress);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.textBoxAge);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBoxName);
            this.Controls.Add(this.dataGridView1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "Form1";
            this.Text = "员工管理";
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.TextBox textBoxName;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox textBoxAge;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox textBoxAddress;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox textBoxEmployeeNumber;
        private System.Windows.Forms.DateTimePicker dateTimePicker1;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Button buttonQuery;
        private System.Windows.Forms.Button buttonAdd;
    }
}

Nuget安装Sqlsugar

配置Sqlsugar

新建配置类

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

namespace WindowsFormsApp3
{
    public class UtilDbConn
    {
        public static SqlSugarClient GetDbConnection()
        {
            // 我的主机IP地址
            string strServer = "192.168.0.105";
            // 我创建的数据库
            string strDataBase = "MESDB";
            // 数据库登录账号
            string strUid = "sa";
            // 数据库登录密码
            string strPwd = "root";
            //创建数据库对象 (用法和EF Dappper一样通过new保证线程安全)
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = $"server={strServer};uid={strUid};pwd={strPwd};database={strDataBase}",
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true //自动释放连接池, 写代码就不需要考虑 open close
            });
            return Db;
        }
    }
}

添加配置类类型的成员变量

private readonly SqlSugarClient db = UtilDbConn.GetDbConnection();

生成实体类

执行命令代码

// 参数1代表存放位置 参数2代表命名空间
db.DbFirst.IsCreateAttribute().CreateClassFile(@"D:\DevelopApplication\Winfrom", "WindowsFormsApp3");

创建单元测试类执行命令代码

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using WindowsFormsApp3;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var db = UtilDbConn.GetDbConnection();
            // 参数1代表存放位置 参数2代表命名空间
            db.DbFirst.IsCreateAttribute().CreateClassFile(@"D:\DevelopApplication\Winfrom", "WindowsFormsApp3");
        }
    }
}

指定位置下生成了数据库中所有表的实体类 我的数据库只建立了一个表 所以只生成一个实体类

实体类添加到项目中

using System;
using System.Linq;
using System.Text;
using SqlSugar;

namespace WindowsFormsApp3
{
    ///<summary>
    ///
    ///</summary>
    [SugarTable("tbEmployee")]
    public partial class tbEmployee
    {
           public tbEmployee(){


           }
           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           public string Name {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           public int Age {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           public string Address {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           public string EmployeeNumber {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           public DateTime OnboardingTime {get;set;}

    }
}

CRUD-新增

验证

/// <summary>
/// 新增
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAdd_Click(object sender, EventArgs e)
{
    var result = db.Insertable(new tbEmployee()
    {
        Name = textBoxName.Text,
        Age = int.Parse(textBoxAge.Text),
        Address = textBoxAddress.Text,
        EmployeeNumber = textBoxEmployeeNumber.Text,
        OnboardingTime = DateTime.Parse(dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss "))
    }).ExecuteCommand();
}

数据库可以查询到插入的数据

CRUD-删除

CRUD-修改

CRUD-查询

标签:C#,System,笔记,Forms,Windows,new,Drawing,SqlSugar,Size
From: https://blog.csdn.net/qq_39586459/article/details/143284874

相关文章

  • CSP-S 2024 游记
    Day0出发。在车上随便写了几题。到了酒店之后本来想调出来正在写的那道题就睡觉的,结果调到0:10都没调出来/fn,直接睡了。Day1早上起来吃完早餐回房间接着写题。然后睡了\(30\)min,然后吃午饭。然后去考场。然后开考了。开考前还是一如既往的不许动鼠标键盘什么的。没事......
  • sicp每日一题[2.72]
    Exercise2.72ConsidertheencodingprocedurethatyoudesignedinExercise2.68.Whatistheorderofgrowthinthenumberofstepsneededtoencodeasymbol?Besuretoincludethenumberofstepsneededtosearchthesymbollistateachnodeencounter......
  • React-Router-Dom6 最佳实践
    React-Router-Dom6最佳实践一咻世界都变了​关注 6人赞同了该文章​展开目录 react-router-dom6使用之前只使用过一次react-router,目前官方从5开始就已经放弃了原有的react-router库,统一命名为 react-router-dom了实现......
  • React学习笔记(六) Create React App
    React学习笔记(六)CreateReactApp 1、介绍CreateReactApp是官方支持的创建单页应用程序的方法,可以帮助我们快速搭建一个繁杂的脚手架我们可以直接使用命令 npminstallcreate-react-app-g 全局安装CreateReactApp然后使用命令 create-react-app<project-na......
  • Acunetix v24.9 发布下载,新增功能概览
    Acunetixv24.9(Linux,Windows)-Web应用程序安全测试Acunetix|WebApplicationSecurityScanner请访问原文链接:https://sysin.org/blog/acunetix/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.org重要提示AcunetixPremium现在使用日历化版本命名。请......
  • idea激活后提示We could not validate your license xxxx解决办法
    根据网上的破解教程,填入激活密钥后idea总是会提示Wecouldnotvalidateyourlicensexxxx解决办法是配置代码点击激活页面左下角的"Proxysettings"配置一个假的代理服务器点击"Manualproxyconfiguation"->HTTPHostname:127.0.0.1Portnumber:808Noproxyf......
  • HCL AppScan Standard 10.7.0 (Windows) - Web 应用程序安全测试
    HCLAppScanStandard10.7.0(Windows)-Web应用程序安全测试HCLAppScanStandardv10forWindowsMultilingual请访问原文链接:https://sysin.org/blog/appscan-10/查看最新版。原创作品,转载请保留出处。作者主页:sysin.org市场领先的应用程序安全解决方案(SAST、D......
  • WebMagic抓取 table分页数据, table分页时,URL不变
    动态页面爬虫前的准备:https://www.cnblogs.com/maohuidong/p/18517953一:java添加maven依赖:<dependency><groupId>us.codecraft</groupId><artifactId>webmagic-core</artifactId><version>0.7.4</version></dependency>&......
  • Mac保护电池健康,延长电池使用寿命的好方法
    使用Mac的过程中,如何延长电池的使用寿命是大家非常关心的问题,而养成一个良好的充电习惯能够有效的延长电池的使用寿命避免过度充电和过度放电能够有效的保护电池,因此长时间的充电与长时间放点都不可取,但是在日常的使用过程中无法投入过多的精力去关注充放电Battery帮助你控制......
  • 还在担心Mac卸载不干净?XApp帮你干净完成卸载
    Mac的卸载机制非常独特,虽然将app拖拽到废纸篓也能够完成卸载,但是会有很多的文件残留,那么如何卸载干净非常重要XApp,免费的Mac卸载工具,有着强大的垃圾检测机制,检测出更深层的垃圾,卸载更干净,有着两种模式拖拽模式:可以将需要卸载的app拖拽进卸载窗口,即可显示卸载app的关联文件,直......