Web开发:SQLsugar的安装和使用

一、安装

第一步,在你的项目中找到解决方案,右键-管理解决方案的Nuget

第二步,下载对应的包,注意你的框架是哪个就下载哪个的包,一个项目安装一次包即可

点击应用和确定

安装好后会显示sqlsugar的包

二、使用:增删改查

using SqlSugar;
using SqlSugar;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

[SugarTable("TestTable")] // 指定实体类对应的数据库表名
class TestTable
{
    [SugarColumn(IsPrimaryKey = true)] // 指定主键列
    public string Id { get; set; }
    
    public string Name { get; set; }

    public int Age { get; set; }

    public string Content { get; set; }

    public int IsEnable { get; set; }

    public int IsDeleted { get; set; }

    public string Stage { get; set; }

    public string Remarks { get; set; }
}

class Test
{
    public static int AddOrUpdate<T>(SqlSugarClient db,T entity) where T : class, new()
    {
        var entityIdProp = GetEntityIdProperty<T>();
        var entityIdValue = entityIdProp.GetValue(entity);
        var dbEntity = db.Queryable<T>().InSingle(entityIdValue);

        if (dbEntity != null)
        {
            // 根据 ID 查询到了记录,执行更新操作
            return db.Updateable(entity).ExecuteCommand();
        }
        else
        {
            // 根据 ID 没有查询到记录,执行插入操作
            return db.Insertable(entity).ExecuteCommand();
        }
    }

    public static PropertyInfo GetEntityIdProperty<T>() where T : class, new()
    {
        var entityType = typeof(T);
        var properties = entityType.GetProperties();

        foreach (var property in properties)
        {
            var attribute = Attribute.GetCustomAttribute(property, typeof(SqlSugar.SugarColumn)) as SqlSugar.SugarColumn;

            if (attribute != null && attribute.IsPrimaryKey)
            {
                return property;
            }
        }

        throw new Exception($"实体类型 {entityType.FullName} 没有定义主键");
    }

    static void Main(string[] args)
    {
        // 创建 SqlSugar 实例
        SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = "server = DESKTOP-FTH2P3S; Database = TestDb; Trusted_Connection = SSPI;", // 数据库连接字符串
            DbType = DbType.SqlServer, // 数据库类型
            IsAutoCloseConnection = true, // 是否自动关闭数据库连接
        });

        // 1.插入数据
        var model = new TestTable()
        {
            Id = Guid.NewGuid().ToString(),
            Name = "Tom",
            Age = 18,
            Content = "Hello World",
            IsEnable = 1,
            IsDeleted = 0,
            Stage = "Stage 1",
            Remarks = "Test"
        };
        int insert_code = db.Insertable(model).ExecuteCommand();//返回影响行数

        // 2.查询数据
        var list = db.Queryable<TestTable>().ToList();

        // 3.自定义查询SQL
        var result = db.SqlQueryable<TestTable>("SELECT * FROM TestTable WHERE Age > 30").ToList();

        // 4.更新数据(先查询实体,然后对需修改的值赋值,再更新)
        var updateModel = db.Queryable<TestTable>().Where(it => it.Id == "8ffd64fc-8aea-4641-a57b-d957ad0dd229").First();
        if (updateModel != null)
        {
            updateModel.Name = "Jerry";
            var update_code = db.Updateable(updateModel).ExecuteCommand();//返回影响行数
        }

        // 5.删除数据
        var delete_code = db.Deleteable<TestTable>().Where(it => it.Id == "8ffd64fc-8aea-4641-a57b-d957ad0dd229").ExecuteCommand();//返回影响行数

        //6.自主封装的方法,有则添加无则插入(根据主键ID匹配)
        var updateModel2 = new TestTable();
        updateModel2.Id = "8ffd64fc-8aea-4641-a57b-d957ad0dd229";
        updateModel2.Name = "SuSu";
        int a = AddOrUpdate<TestTable>(db, updateModel2);//返回影响行数

    }
}

【备注】AddOrUpdate是自己写的方法。

三、表的自定义查询SQL

    /// <summary>
    /// 表的自定义查询
    /// </summary>
    /// <returns></returns>
    public List<T> QueryBySQL<T>(string sql) where T : class,new()
    {
        return db.SqlQueryable<T>(sql).ToList();
    }

四、通过数据库生成C#实体类

运行以下代码即可,其中CreateClassFile里面的路径可以写一个文件夹的路径

using ConsoleApp1;
using SqlSugar;

class Program
{

    static void Main()
    {
        // 配置数据库连接字符串
        string connectionString = "server = DESKTOP-FTH2P3S; Database = EnterpriseHRM; Trusted_Connection = SSPI;";
        var db = new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = connectionString,
            DbType = DbType.SqlServer, // 根据你的数据库类型设置 DbType
            IsAutoCloseConnection = true, // 自动释放连接
            InitKeyType = InitKeyType.Attribute // 使用 Attribute 方式获取 Key
        });

        // 生成实体类
        db.DbFirst // 使用 DbFirst 工具
            .IsCreateAttribute() // 使用属性生成实体类
            .CreateClassFile("F:\\C_program\\sqlsugar_demo\\repos\\ConsoleApp1\\ConsoleApp1\\GenerateModel"); // 输出路径
    }
}

 生成效果如下所示

本地路径 

 

五、小结

1.连接字符串(db)

SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = "server = DESKTOP-FTH2P3S; Database = TestDb; Trusted_Connection = SSPI;", // 数据库连接字符串
            DbType = DbType.SqlServer, // 数据库类型
            IsAutoCloseConnection = true, // 是否自动关闭数据库连接
        });

2.五大方法(增删改查+自定义SQL查询) 

db.Insertable(model).ExecuteCommand();
db.Updateable(updateModel).ExecuteCommand();
db.Queryable<TestTable>().ToList();
db.Deleteable<TestTable>().ExecuteCommand();
db.SqlQueryable<TestTable>("sql语句").ToList();

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值