首页 > 数据库 >ORM之SqlSugar简单示例

ORM之SqlSugar简单示例

时间:2024-08-02 17:49:44浏览次数:11  
标签:Task return 示例 await ORM ex using public SqlSugar

示例结构

 下面给出示例代码,安装编码框架可扩展

IDal接口定义

namespace ORMRepository
{
    /// <summary>
    /// 数据库访问接口
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IDal<T>
    {
        /// <summary>
        /// 通过id获取数据
        /// </summary>
        /// <returns></returns>
        Task<T> GetByIdAsync(string id);
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        Task<List<T>> GetAllAsync();
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        Task<bool> InsertAsync(T t);
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        Task<bool> UpdateAsync(T t);
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        Task<bool> DeleteAsync(T t);
    }
}
namespace ORMRepository
{
    internal class DbConnectionFactory
    {
        internal static string ConnectionString;
        public static SqlSugarClient GetDbConnection()
        {
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.Sqlite,
                ConnectionString = ConnectionString,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,
            });
            
            //SqlSugar默认会创建
            //if (!File.Exists(DbFileFullName))
            //{
            //db.DbMaintenance.CreateDatabase();
            //}
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                //保留日志
                Debug.WriteLine(sql);
            };
            return db;
        }
    }
}
namespace ORMRepository
{
    /// <summary>
    /// 访问数据模板
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public abstract class BaseDalTemplate<TEntity> where TEntity : class, new()
    {
        public abstract Task<TEntity> GetByIdAsync(string id);
        /// <summary>
        /// 管理队列锁
        /// </summary>
        private readonly SemaphoreSlim _parallelExecuteLock;
        protected BaseDalTemplate()
        {
            try
            {
                _parallelExecuteLock = new SemaphoreSlim(1);
                using (var client = DbConnectionFactory.GetDbConnection())
                {
                    //代码先行
                    client.CodeFirst.InitTables<TEntity>();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

        /// <summary>
        /// 根据lambda表达式获取实体
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public async Task<List<TEntity>> GetByExpressionAsync(Expression<Func<TEntity, bool>> expression)
        {
            try
            {
                await _parallelExecuteLock.WaitAsync();
                using (var client = DbConnectionFactory.GetDbConnection())
                {
                    return await client.Queryable<TEntity>().Where(expression).ToListAsync();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                _parallelExecuteLock.Release();
            }
            return new List<TEntity>();
        }

        /// <summary>
        /// 获取所有实体
        /// </summary>
        /// <returns></returns>
        public async Task<List<TEntity>> GetAllAsync()
        {
            try
            {
                await _parallelExecuteLock.WaitAsync();
                using (var client = DbConnectionFactory.GetDbConnection())
                {
                    return await client.Queryable<TEntity>().ToListAsync();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                _parallelExecuteLock.Release();
            }
            return new List<TEntity>();
        }

        /// <summary>
        /// 插入实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(TEntity t)
        {
            try
            {
                await _parallelExecuteLock.WaitAsync();
                using (var client = DbConnectionFactory.GetDbConnection())
                {
                    var executeCommand = await client.Insertable(t).ExecuteCommandAsync();
                    return executeCommand > 0;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                _parallelExecuteLock.Release();
            }
            return false;
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(TEntity t)
        {
            try
            {
                await _parallelExecuteLock.WaitAsync();
                using (var client = DbConnectionFactory.GetDbConnection())
                {
                    var executeCommand = await client.Updateable(t).ExecuteCommandAsync();
                    return executeCommand > 0;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                _parallelExecuteLock.Release();
            }
            return false;
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(TEntity t)
        {
            try
            {
                await _parallelExecuteLock.WaitAsync();
                using (var client = DbConnectionFactory.GetDbConnection())
                {
                    var executeCommand = await client.Deleteable(t).ExecuteCommandAsync();
                    return executeCommand > 0;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                _parallelExecuteLock.Release();
            }
            return false;
        }
    }
}
namespace ORMRepository.Repository.DB
{
    [SugarTable("TB_TestInfo")]
    internal class TestInfoEntity
    {
        [SugarColumn(IsPrimaryKey = true)]
        public string CommandId { get; set; }
        [SugarColumn(IsNullable = true)]
        public string DownloadUrl { get; set; }

        [SugarColumn(IsNullable = true)]
        public string Md5 { get; set; }
        public DateTime CreateTime { get; set; } = DateTime.Now;
        public int TotalSize { get; set; }
        public byte Status { get; set; }

        //[SugarColumn(ColumnDataType ="boolean")]
        public bool CanOverlay { get; set; }
    }
}
namespace ORMRepository.Repository.DAL
{
    internal class TestInfoDal : BaseDalTemplate<TestInfoEntity>, IDal<TestInfoEntity>
    {
        public override async Task<TestInfoEntity> GetByIdAsync(string id)
        {
            return (await GetByExpressionAsync(obj => obj.CommandId == id)).FirstOrDefault();
        }
    }
}

示例调用

using ORMRepository.Repository.DAL;
using ORMRepository.Repository.DB;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;

namespace ORMRepository
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// 文件推送
        /// </summary>
        internal static Lazy<TestInfoDal> TestInfoDal;
        public App()
        {
            DbConnectionFactory.ConnectionString = $"DataSource={Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"ORMRepository.sqlite")}";
            TestInfoDal = new Lazy<TestInfoDal>();
            TestAsync();
        }

        public async Task TestAsync()
        {
            var testInfoDal = TestInfoDal.Value;
            var testInfoEntities = await testInfoDal.GetAllAsync();
            var testInfoEntity = new TestInfoEntity
            {
                CommandId = Guid.NewGuid().ToString()
            };
            await testInfoDal.InsertAsync(testInfoEntity);
        }
    }
}

 

标签:Task,return,示例,await,ORM,ex,using,public,SqlSugar
From: https://www.cnblogs.com/terryK/p/18339295

相关文章

  • antd react form.list动态增减表单项Switch受控
    importReact,{useState}from'react';import{Form,Input,Switch,Button}from'antd';constDemo=()=>{const[switches,setSwitches]=useState({});constonFinish=(values)=>{console.log('Received......
  • Pytorch笔记|小土堆|P10-13|transforms
    transforms对图像进行改造最靠谱的办法:根据help文件自行学习transforms包含哪些工具(类)以及如何使用————————————————————————————————————自学一个类时,应关注:1、如何使用各种工具(类)的使用思路:创建对象(实例化)——>传入参数,调用函数(如有__......
  • 深度学习扫盲——Transforms
    在PyTorch中,torchvision是一个常用的库,它提供了对图像和视频数据的处理功能,包括数据加载、转换等。transforms是torchvision.transforms模块的一部分,它定义了一系列的图像转换操作,这些操作可以单独使用或者组合成转换序列(通过transforms.Compose),以便于在数据加载时自动应用到图像......
  • 白盒测试基础与实践:Python示例及流程图设计
    文章目录前言一、白盒测试是什么?主要特点常用方法优点缺点二、白盒测试常用技术语句覆盖判定覆盖条件覆盖判定/条件覆盖条件组合覆盖路径覆盖三、程序流程图设计四、测试用例设计1.基本路径法2.语句覆盖3.判断覆盖4.条件覆盖5.判断/条件覆盖6.条件组合覆盖总结......
  • Seurat-SCTransform与harmony整合学习
    目录基础介绍SCTransform与harmony联合代码测试1)报错解决2)SCTransform标准化3)harmony去批次基础介绍源于Rtips:Seurat之SCTransform方法原理(qq.com)Seurat对象在经过SCTransform处理后会增加一个SCT的Assay,里面的scaled.data就是经过scale之后的pearsonresidual值......
  • 如何理解词向量、Transformer模型以及三个权重矩阵
    词向量与transformer 生成词向量的过程和训练Transformer的过程是两个不同的过程,但它们都是自然语言处理中的重要组成部分。#词向量的生成词向量(如Word2Vec、GloVe、FastText等)通常是通过预训练的词嵌入模型得到的。这些模型在大规模文本数据上训练,捕捉词与词之间的语义关系,......
  • Transformer预测模型及其Python和MATLAB实现
    ###一、背景在自然语言处理(NLP)领域,传统的序列到序列(Seq2Seq)模型大多依赖于循环神经网络(RNN)和长短期记忆(LSTM)网络。这些模型虽然在许多任务中取得了成功,但由于其计算效率低下以及长距离依赖关系处理的不足,导致模型训练时间漫长,并在处理较长文本时效果不佳。2017年,Vaswani等人......
  • 压力测试(caliper具体步骤+示例)
    Caliper压力测试(具体步骤+示例)一、Caliper压力测试指南1.环境要求(1)配置基本环境部署Caliper的计算机需要有外网权限;解决方法:#通常情况下,DNS服务器由你的网络配置提供。你可以查看当前的DNS设置:cat/etc/resolv.confoot@thy-virtual-machine:/home/thy/fisc......
  • OAF export data from VO in xlsx format
    InthisarticlewearegoingtoseehowtoexportviewobjectinMicrosoftofficeexcelxlsxformatToexportwithxlsxformatfewbasicthingsneededareJarfiles(Listofjari'veusedisshowninbelowscreenshot)ForbetterunderstandingI’lli......
  • javascript: vue create project in WebStorm
     route/index.js import{createRouter,createWebHistory,createWebHashHistory}from'vue-router'importHomeViewfrom'../views/HomeView.vue'importAboutViewfrom"../views/AboutView.vue";constrouter=createRouter(......