SQLSUGAR自学篇(四):SQLSUGAR之仓储模式,以及基本的增删改查

#代码星辉·七月创作之星挑战赛#

什么是仓储模式?

仓储模式(Repository Pattern)是一种数据访问抽象层,它在领域模型数据访问逻辑之间创建了一个隔离层。通过仓储,你的业务逻辑代码无需直接与数据库交互,而是通过类似集合的接口操作实体对象。

为什么需要仓储模式?

  1. 解耦数据访问:业务逻辑不再依赖具体的数据库操作,降低了代码间的耦合度。
  2. 提高可测试性:可以轻松替换仓储实现(如使用内存仓储进行单元测试)。
  3. 统一数据访问:集中管理数据访问逻辑,避免重复代码。
  4. 便于切换 ORM:如果未来需要更换 ORM(如从 SqlSugar 切换到 EF),只需修改仓储层实现。

大白话解释:

仓储模式是一种设计模式,它充当数据访问层业务逻辑层之间的桥梁。简单来说,它把数据操作(增删改查)封装到一个类中,让业务代码只需要调用这些方法,而不需要关心底层数据库是如何实现的。 

为什么需要单独建一个这个类而不直接写sql原生语句呢?

  • 当数据库类型变化时(如从 SQL Server 切换到 MySQL),你需要修改所有地方的代码。
  • 测试时很难模拟数据库操作。
  • 代码重复率高,难以维护。

使用仓储模式可以解决这些问题!!!!!

实现仓储模式的步骤

三步走战略,网上查的资料汇总下来就是这些

  1. 数据访问层

    • IRepository<TEntity>接口和RepositoryBase<TEntity>实现类,这属于数据访问层。
    • UserModel类业务模块聚合仓储。
  2. 共享层

    • UserInfo类作为数据实体,通常属于数据层或共享层。
  3. 数据库配置层

    • SqliteDbHelper类负责数据库连接配置,属于基础设施。
数据访问层: 

IRepository接口将数据访问操作(如查询、插入、更新)抽象为方法,使业务逻辑层无需关心数据来源(数据库、文件、API 等)或具体实现方式。

优点:业务代码只需依赖接口,无需依赖具体的数据库访问实现,降低耦合度。

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

namespace SqlSugarToSqlite.Infrastructure
{
    //创建仓储接口
    public interface IRepository<TEntity> where TEntity : class, new()
    {
        #region 查询操作
        TEntity GetById(object id);
        List<TEntity> GetAll();
        List<TEntity> Where(Expression<Func<TEntity, bool>> expression);
        #endregion

        #region 增删改操作
        bool Insert(TEntity entity);
        bool Update(TEntity entity);
        bool Delete(TEntity entity);
        #endregion

        #region 批量操作
        int InsertRange(List<TEntity> entities);
        int UpdateRange(List<TEntity> entities);
        int DeleteRange(List<TEntity> entities);
        #endregion

        #region 异步操作
        Task<TEntity> GetByIdAsync(object id);
        Task<List<TEntity>> GetAllAsync();
        Task<int> InsertAsync(TEntity entity);
        Task<int> UpdateAsync(TEntity entity);
        Task<int> DeleteAsync(TEntity entity);
        #endregion


        #region 扩展修改方法
        bool Update(TEntity entity, Expression<Func<TEntity, object>> columns);
        #endregion
    }

}

RepositoryBase 接口是 IRepository<TEntity>的默认实现。它的核心作用是封装通用的数据访问逻辑,避免为每个实体重复编写相同的 CRUD 代码,从而提高代码复用性和可维护性。

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

namespace SqlSugarToSqlite.Infrastructure
{
    //使用SQLSUGAR实现通用仓储
    public class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class, new()
    {
        private readonly SqlSugarClient _db;

        public RepositoryBase(SqlSugarClient db)
        {
            _db = db;
        }

        #region 查询实现
        public TEntity GetById(object id) => _db.Queryable<TEntity>().InSingle(id);

        public List<TEntity> GetAll() => _db.Queryable<TEntity>().ToList();

        public List<TEntity> Where(Expression<Func<TEntity, bool>> expression) =>
            _db.Queryable<TEntity>().Where(expression).ToList();
        #endregion

        #region 增删改实现
        public bool Insert(TEntity entity) => _db.Insertable(entity).ExecuteCommand() > 0;

        public bool Update(TEntity entity) => _db.Updateable(entity).ExecuteCommand() > 0;

        public bool Delete(TEntity entity) => _db.Deleteable(entity).ExecuteCommand() > 0;
        #endregion

        #region 批量操作实现
        public int InsertRange(List<TEntity> entities) => _db.Insertable(entities).ExecuteCommand();

        public int UpdateRange(List<TEntity> entities) => _db.Updateable(entities).ExecuteCommand();

        public int DeleteRange(List<TEntity> entities) => _db.Deleteable(entities).ExecuteCommand();
        #endregion

        #region 异步操作实现
        public async Task<TEntity> GetByIdAsync(object id) => await _db.Queryable<TEntity>().InSingleAsync(id);

        public async Task<List<TEntity>> GetAllAsync() => await _db.Queryable<TEntity>().ToListAsync();

        public async Task<int> InsertAsync(TEntity entity) => await _db.Insertable(entity).ExecuteCommandAsync();

        public async Task<int> UpdateAsync(TEntity entity) => await _db.Updateable(entity).ExecuteCommandAsync();

        public async Task<int> DeleteAsync(TEntity entity) => await _db.Deleteable(entity).ExecuteCommandAsync();
        #endregion

        #region 扩展修改实现
        public bool Update(TEntity entity, Expression<Func<TEntity, object>> columns) =>
            _db.Updateable(entity).UpdateColumns(columns).ExecuteCommand() > 0;
        #endregion
    }
}

UserModel 类的主要逻辑集中在构造函数中,它接收一个 SqlSugarClient 数据库连接实例,并创建 UserInfo 实体的仓储实现类 RepositoryBase<UserInfo>

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

namespace SqlSugarToSqlite.Infrastructure
{
    public class UserModel
    {
        public IRepository<UserInfo> UserInfoRepository { get; private set; }

        public UserModel(SqlSugarClient db)
        {
            UserInfoRepository = new RepositoryBase<UserInfo>(db);
        }
    }
}
共享层

UserInfo 类是一个数据实体模型,主要用于:

  • 映射数据库表 UserInfo 的结构
  • 作为数据载体,在各层之间传输用户相关信息
  • 通过特性(Attribute)定义实体与数据库的映射规则
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlSugarToSqlite.SqlConfig
{
    [SugarTable("UserInfo")] // 指定数据库表名
    public class UserInfo
    {
        /// <summary>
        /// 主键ID,确保IsIdentity=true,且不要手动设置此值
        /// </summary>
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }

        /// <summary>
        /// 索引字段
        /// </summary>
        [SugarColumn(ColumnName = "index")] // 与数据库字段名映射
        public string Index { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
        /// <summary>
        /// 余额
        /// </summary>
        public float Amount { get; set; }
        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// 地区
        /// </summary>
        public string Region { get; set; }

        /// <summary>
        /// 电话号码
        /// </summary>
        public string Phonenumber { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; } = DateTime.Now;
    }
}

对应在数据库中的表单 

数据库配置层

SqliteDbHelper 是一个用于管理 SQLite 数据库连接的辅助类,其核心作用是封装数据库连接的创建、配置和单例管理,确保整个应用程序中使用同一个数据库连接实例,避免资源浪费和连接泄漏。

using SqlSugar;
using System;
using System.IO;
using System.Reflection;

namespace SqlSugarToSqlite.SqlConfig
{
    public class SqliteDbHelper
    {
        private static SqlSugarClient _db;
        private static readonly object LockObject = new object();

        public static SqlSugarClient Db
        {
            get
            {
                if (_db == null)
                {
                    lock (LockObject)
                    {
                        if (_db == null)
                        {
                            InitializeDb();
                        }
                    }
                }
                return _db;
            }
        }

        private static void InitializeDb()
        {
            try
            {
                // 读取配置文件
                string configPath = Path.Combine(
                    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                    "Config",
                    "ConnectionConfig.json");

                if (!File.Exists(configPath))
                {
                    throw new FileNotFoundException("找不到数据库配置文件", configPath);
                }

                // 解析JSON配置
                dynamic config = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(configPath));
                string connectionString = config.ConnectionStrings.SqliteConnection.ToString();

                // 确保数据库文件路径正确
                string dbPath = connectionString.Split('=')[1].Split(';')[0].Trim();
                if (!Path.IsPathRooted(dbPath))
                {
                    dbPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dbPath);
                }

                if (!File.Exists(dbPath))
                {
                    throw new FileNotFoundException("找不到SQLite数据库文件", dbPath);
                }

                // 创建SqlSugar连接配置
                _db = new SqlSugarClient(new ConnectionConfig
                {
                    ConnectionString = $"Data Source={dbPath}",
                    DbType = DbType.Sqlite,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败: {ex.Message}");
                throw;
            }
        }
    }
}
 页面设计

 ceshiWareHouseWindow.xaml前端代码

<Window x:Class="SqlSugarToSqlite.ceshiWareHouseWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SqlSugarToSqlite"
        mc:Ignorable="d"
        Title="ceshiWareHouseWindow" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="us_Datagrid" Height="250" VerticalAlignment="Top"/>
        <StackPanel Orientation="Horizontal" Height="50" VerticalAlignment="Bottom" Margin="0,0,0,100">
            <Label Width="80" Content="编号" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="15"/>
            <TextBox x:Name="txt_Index" Width="100" FontSize="15" VerticalContentAlignment="Center" Background="AliceBlue"/>
            <Label Width="80" Content="姓名" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="15"/>
            <TextBox x:Name="txt_Name" Width="100" FontSize="15" VerticalContentAlignment="Center" Background="AliceBlue"/>
            <Label Width="80" Content="年龄" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="15"/>
            <TextBox x:Name="txt_Age" Width="100" FontSize="15" VerticalContentAlignment="Center" Background="AliceBlue"/>
            
        </StackPanel>
        <StackPanel Orientation="Horizontal" Height="50" VerticalAlignment="Bottom" Margin="0,0,0,50">
            <Label Width="80" Content="Email" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="15"/>
            <TextBox x:Name="txt_Email" Width="100" FontSize="15" VerticalContentAlignment="Center" Background="AliceBlue"/>
            <Label Width="80" Content="Region" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="15"/>
            <TextBox x:Name="txt_Region" Width="100" FontSize="15" VerticalContentAlignment="Center" Background="AliceBlue"/>
            <Label Width="80" Content="Phone" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="15"/>
            <TextBox x:Name="txt_Phone" Width="100" FontSize="15" VerticalContentAlignment="Center" Background="AliceBlue"/>
            <Label Width="80" Content="Amount" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="15"/>
            <TextBox x:Name="txt_Amount" Width="100" FontSize="15" VerticalContentAlignment="Center" Background="AliceBlue"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" Height="40" Margin="0,0,0,0">

            <Button Content="增加" Width="150" Click="Add_Click" VerticalContentAlignment="Center" FontSize="15"/>
            <Button Content="删除" Width="150" Click="Remove_Click" VerticalContentAlignment="Center" FontSize="15" Margin="10,0,0,0"/>
            <Button Content="更改" Width="150" Click="Change_Click" VerticalContentAlignment="Center" FontSize="15" Margin="10,0,0,0"/>
            <TextBox x:Name="Search_Text" VerticalContentAlignment="Center"  Width="150" Margin="10,0,0,0" Background="AliceBlue"/>
            <Button Content="查询" Width="50" Click="Search_Click" VerticalContentAlignment="Center" FontSize="15" Margin="10,0,0,0"/>
        </StackPanel>
    </Grid>
</Window>

样式

 ceshiWareHouseWindow.cs

using SqlSugar;
using SqlSugarToSqlite.Infrastructure;
using SqlSugarToSqlite.SqlConfig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SqlSugarToSqlite
{
    /// <summary>
    /// ceshiWareHouseWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ceshiWareHouseWindow : Window
    {
        private SqlSugarClient _db;
        private UserModel _userModel;
        public ceshiWareHouseWindow()
        {
            InitializeComponent();
            //获取数据库连接
           _db = SqliteDbHelper.Db;
            //创建用户模块
            _userModel = new UserModel(_db);
            RefreshDataGrid();
            us_Datagrid.SelectionChanged += us_Datagrid_SelectionChanged;
        }
        private void RefreshDataGrid()
        {
            try
            {
                //仓储模式查询所有数据
                var usinfos= _userModel.UserInfoRepository.GetAll();
                us_Datagrid.ItemsSource = usinfos;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void us_Datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedUser = us_Datagrid.SelectedItem as UserInfo;
            if (selectedUser != null)
            {
                txt_Index.Text = selectedUser.Index;
                txt_Name.Text = selectedUser.Username;
                txt_Age.Text = selectedUser.Age.ToString();
                txt_Email.Text = selectedUser.Email;
                txt_Region.Text = selectedUser.Region;
                txt_Phone.Text = selectedUser.Phonenumber;
                txt_Amount.Text = selectedUser.Amount.ToString();
            }
        }
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var newUser = new UserInfo
                {
                    Index = txt_Index.Text,
                    Username = txt_Name.Text,
                    Age = int.Parse(txt_Age.Text),
                    Email = txt_Email.Text,
                    Region = txt_Region.Text,
                    Phonenumber = txt_Phone.Text,
                    CreateTime = DateTime.Now,
                    Amount = float.Parse(txt_Amount.Text),
                };
                //仓储模式增加用户
               _userModel.UserInfoRepository.Insert(newUser);

                MessageBox.Show("用户添加成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                RefreshDataGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加用户失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Remove_Click(object sender, RoutedEventArgs e)
        {
            // 获取选中的用户
            var selectedUser = us_Datagrid.SelectedItem as UserInfo;
            if (selectedUser == null)
            {
                MessageBox.Show("请先选择要删除的用户", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 确认删除
            if (MessageBox.Show($"确定要删除用户 '{selectedUser.Username}' 吗?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                return;
            }

            try
            {

                //var db = SqliteDbHelper.Db;
                //// 原生删除功能
                //int affectedRows = db.Deleteable(selectedUser).ExecuteCommand();

                //仓储模式下删除功能
               var isok= _userModel.UserInfoRepository.Delete(selectedUser);
                if (isok)
                {
                    MessageBox.Show("用户删除成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    RefreshDataGrid(); // 重新加载数据
                }
                else
                {
                    MessageBox.Show("用户删除失败,可能已被其他操作删除", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除用户失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Change_Click(object sender, RoutedEventArgs e)
        {
            // 获取选中的用户
            var selectedUser = us_Datagrid.SelectedItem as UserInfo;
            if (selectedUser == null)
            {
                MessageBox.Show("请先选择要修改的用户", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                // 更新用户信息
                selectedUser.Index = txt_Index.Text;
                selectedUser.Username = txt_Name.Text;
                selectedUser.Age = int.Parse(txt_Age.Text);
                selectedUser.Email = txt_Email.Text;
                selectedUser.Region = txt_Region.Text;
                selectedUser.Phonenumber = txt_Phone.Text;
                selectedUser.CreateTime = DateTime.Now;
                selectedUser.Amount = float.Parse(txt_Amount.Text);

                //var db = SqliteDbHelper.Db;
                //// 执行更新
                //int affectedRows = db.Updateable(selectedUser).ExecuteCommand();

                // 使用仓储模式更新(只更新修改的字段)
                bool isUpdated = _userModel.UserInfoRepository.Update(
                    selectedUser,
                    u => new { u.Index, u.Username, u.Age, u.Email, u.Region, u.Phonenumber, u.CreateTime, u.Amount }
                );

                //全部更新
                bool isok = _userModel.UserInfoRepository.Update(selectedUser);

                //注意 全部更新虽然看起来简洁,但是他会覆盖原来的所有内容,消耗较大
                if (isUpdated)
                {
                    MessageBox.Show("用户信息修改成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    RefreshDataGrid(); // 重新加载数据
                }
                else
                {
                    MessageBox.Show("用户信息修改失败,数据未变更", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"修改用户失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Search_Click(object sender, RoutedEventArgs e)
        {
            string searchKeyword = Search_Text.Text.Trim();
            if (string.IsNullOrEmpty(searchKeyword))
            {
                // 无搜索关键词时显示全部数据
                RefreshDataGrid();
                return;
            }

            try
            {
                //var db = SqliteDbHelper.Db;

                //// 多字段模糊查询(Index、Username、Email、Region、Phonenumber)
                //var users = db.Queryable<UserInfo>()
                //    .Where(u =>
                //        u.Index.Contains(searchKeyword) ||
                //        u.Username.Contains(searchKeyword) ||
                //        u.Email.Contains(searchKeyword) ||
                //        u.Region.Contains(searchKeyword) ||
                //        u.Phonenumber.Contains(searchKeyword)
                //    )
                //    .ToList();
                //仓储模式下查询
                var users = _userModel.UserInfoRepository.Where(u =>
                    u.Index.Contains(searchKeyword) ||
                    u.Username.Contains(searchKeyword) ||
                    u.Email.Contains(searchKeyword) ||
                    u.Region.Contains(searchKeyword) ||
                    u.Phonenumber.Contains(searchKeyword)
                ).ToList();

                us_Datagrid.ItemsSource = users;
                MessageBox.Show($"共找到 {users.Count} 条匹配记录", "搜索结果", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

    }
}
代码片段对比:

实现查询

//原生查询          
var allUsers = _db.Queryable<UserInfo>().ToList();           
us_Datagrid.ItemsSource = allUsers;

//仓储模式查询所有数据
var usinfos= _userModel.UserInfoRepository.GetAll();
us_Datagrid.ItemsSource = usinfos;

实现增加数据

 //仓储模式增加用户
_userModel.UserInfoRepository.Insert(newUser);

//原生增加数据
 var db = SqliteDbHelper.Db;
 db.Insertable(newUser).ExecuteCommand();

实现删除

//原生删除
var db = SqliteDbHelper.Db;
// 执行删除
int affectedRows = db.Deleteable(selectedUser).ExecuteCommand();
//仓储模式下删除功能
var isok= _userModel.UserInfoRepository.Delete(selectedUser);

 实现更新

var db = SqliteDbHelper.Db;
// 执行更新
int affectedRows = db.Updateable(selectedUser).ExecuteCommand();
// 使用仓储模式更新(只更新修改的字段)
bool isUpdated = _userModel.UserInfoRepository.Update(
        selectedUser,
        u => new { u.Index, 
        u.Username, 
        u.Age, 
        u.Email, 
        u.Region,
        u.Phonenumber, 
        u.CreateTime, 
        u.Amount });
//全部更新
bool isok = _userModel.UserInfoRepository.Update(selectedUser);
//注意 全部更新虽然看起来简洁,但是他会覆盖原来的所有内容,消耗较大

这里的更新有两种方式 部分更新和全部更新

部分字段更新

 bool isUpdated = _userModel.UserInfoRepository.Update  (

                         selectedUser,u => new { u.Username,...... });

优点缺点
性能更优:仅传输和更新必要字段,减少数据库 IO 和网络传输量。代码复杂度高:需要显式指定更新字段,尤其当更新字段较多时,代码冗长(如用户代码中需列出 8 个字段)。
数据安全性高:避免未修改字段被意外覆盖(如并发场景下其他线程修改的字段不会被当前操作覆盖)。维护成本高:当实体字段变更时,需要同步修改更新字段的表达式,容易遗漏。
资源消耗低:减少 SQL 语句编译和执行开销,尤其适合大表或高频更新场景。可读性较差:表达式语法(如 u => new { u.Field1, u.Field2 })不够直观,调试难度较高。

全部字段更新 

优点缺点
代码简洁:直接传入实体即可完成更新,无需显式指定字段,代码量少。性能较差:无论字段是否修改,都会更新所有字段,增加数据库负担。
实现简单:仓储接口设计更简洁,无需额外定义带字段参数的 Update 方法。数据风险高:若实体中包含未修改的字段(如其他线程更新的数据),会被当前操作覆盖,导致数据丢失。
可读性好:方法调用直观(Update(entity)),新人容易理解。网络开销大:传输整个实体数据,尤其当实体包含大字段(如文本、二进制数据)时,效率低下。
实现效果

使用起来和我自学篇一大差不差,都是实现基本的增删改查,如果需要用到特别复杂的功能,那么就需要在接口里面自己写

如何选择:仓储模式 vs 原生 SqlSugar

场景推荐方式理由
快速原型开发原生 SqlSugar代码简洁,开发效率高
小型单模块应用轻量级仓储模式适度抽象,便于维护
中大型复杂项目完整仓储模式解耦架构,支持团队协作
需要频繁切换数据库仓储模式屏蔽数据库差异
追求极致性能原生 SqlSugar 或存储过程减少抽象层性能损耗

总结:仓储模式的本质与价值

仓储模式的核心不是 “封装数据库操作”,而是通过抽象层建立 “领域模型与数据存储的映射契约”。它让开发者聚焦业务逻辑,同时保持数据访问的灵活性与可维护性。在实际应用中,需根据项目规模权衡架构复杂度,避免为了模式而模式 —— 合适的架构才是最好的架构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值