当前位置: 首页 > article >正文

数据库与仓储

数据库与仓储位置Source/DataBases项目作用H.DataBases.Share数据库共享代码。H.DataBases.SqliteSqlite 支持。H.DataBases.SqlServerSQL Server 支持。Repository 相关H.Extensions.DataBase.Repository H.Presenters.Repository H.Controls.RepositoryBox H.Test.RepositoryPresenter思路数据库模型 - 仓储服务 - Presenter - RepositoryBox 页面适合快速生成 CRUD 管理页面。DataBases 数据库系统详解一、数据库系统概述WPF-Control 的数据库系统基于Entity Framework构建提供了完整的仓储模式实现支持 Sqlite 和 SQL Server 两种数据库。核心架构数据库模型 → 仓储服务 → Presenter → RepositoryBox 页面这种设计使得开发者可以快速生成 CRUD 管理页面无需从头编写数据库操作代码。二、数据库项目结构2.1 项目组成Source/DataBases/ ├── H.DataBases.Share/ # 共享代码 │ ├── Provider/ │ │ ├── RepositoryBase.cs # 仓储基类 │ │ ├── DbContextRepository.cs # DbContext仓储 │ │ └── StringRepositoryBase.cs # 字符串主键仓储 │ ├── DbConnectServiceBase.cs # 数据库连接服务基类 │ ├── DbDisconnectService.cs # 数据库断开服务 │ ├── DbSettableBase.cs # 数据库设置基类 │ └── IDbSetting.cs # 数据库设置接口 ├── H.DataBases.Sqlite/ # Sqlite 支持 └── H.DataBases.SqlServer/ # SQL Server 支持2.2 Repository 相关模块模块作用H.Extensions.DataBase.Repository可绑定的仓储实现H.Presenters.Repository仓储展示器H.Controls.RepositoryBox仓储数据页面控件H.Test.RepositoryPresenter测试用仓储展示器三、核心概念3.1 实体基类框架提供了多种实体基类// 通用实体基类publicabstractclassEntityBaseTPrimaryKey:IEntityBaseTPrimaryKey{publicTPrimaryKeyID{get;set;}}// 字符串主键实体publicabstractclassStringEntityBase:EntityBasestring{publicStringEntityBase(){IDGuid.NewGuid().ToString();}}// Guid主键实体publicabstractclassGuidEntityBase:EntityBaseGuid{publicGuidEntityBase(){IDGuid.NewGuid();}}3.2 仓储接口publicinterfaceIRepositoryTEntity,TPrimaryKey{// 查询TaskListTEntityGetListAsync();TaskTEntityGetByIDAsync(TPrimaryKeyid);TaskTEntityFirstOrDefaultAsync(ExpressionFuncTEntity,boolpredicate);// 新增TaskintInsertAsync(TEntityentity,boolautoSavetrue);TaskintInsertRangeAsync(paramsTEntity[]entity);// 更新TaskintUpdateAsync(TEntityentity,boolautoSavetrue);// 删除TaskintDeleteAsync(TEntityentity,boolautoSavetrue);TaskintDeleteByIDAsync(TPrimaryKeyid,boolautoSavetrue);// 分页TaskTupleListTEntity,intLoadPageList(intstartPage,intpageSize,ExpressionFuncTEntity,boolwherenull,ExpressionFuncTEntity,objectordernull);// 保存TaskintSaveAsync();}四、RepositoryBase 详解4.1 仓储基类实现RepositoryBase是所有仓储的基类提供了完整的 CRUD 操作publicabstractclassRepositoryBaseTDbContext,TEntity,TPrimaryKey:IRepositoryTEntity,TPrimaryKeywhereTEntity:EntityBaseTPrimaryKeywhereTDbContext:DbContext{protectedreadonlyTDbContext_dbContext;publicRepositoryBase(TDbContextdbContext){_dbContextdbContext;}// 获取所有实体publicasyncTaskListTEntityGetListAsync(){returnawait_dbContext.SetTEntity().ToListAsync();}// 根据主键获取实体publicasyncTaskTEntityGetByIDAsync(TPrimaryKeyid){returnawait_dbContext.SetTEntity().FirstOrDefaultAsync(CreateEqualityExpressionForId(id));}// 新增实体publicasyncTaskintInsertAsync(TEntityentity,boolautoSavetrue){_dbContext.SetTEntity().Add(entity);if(autoSave)returnawaitSaveAsync();return-1;}// 更新实体publicasyncTaskintUpdateAsync(TEntityentity,boolautoSavetrue){TEntityobjawaitGetByIDAsync(entity.ID);EntityToEntity(entity,obj);// 属性拷贝if(autoSave)returnawaitSaveAsync();return-1;}// 删除实体publicasyncTaskintDeleteAsync(TEntityentity,boolautoSavetrue){_dbContext.SetTEntity().Remove(entity);if(autoSave)returnawaitSaveAsync();return-1;}// 分页查询publicasyncTaskTupleListTEntity,intLoadPageList(intstartPage,intpageSize,ExpressionFuncTEntity,boolwherenull,ExpressionFuncTEntity,objectordernull){IQueryableTEntityresult_dbContext.SetTEntity();if(where!null)resultresult.Where(where);if(order!null)resultresult.OrderBy(order);introwCountawaitresult.CountAsync();ListTEntitydataawaitresult.Skip((startPage-1)*pageSize).Take(pageSize).ToListAsync();returnTuple.Create(data,rowCount);}}4.2 使用示例步骤1创建实体类publicclassUser:StringEntityBase{publicstringName{get;set;}publicstringEmail{get;set;}publicintAge{get;set;}publicDateTimeCreateTime{get;set;}DateTime.Now;}步骤2创建 DbContextpublicclassAppDbContext:DbContext{publicDbSetUserUsers{get;set;}protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder){optionsBuilder.UseSqlite(Data Sourceapp.db);}}步骤3创建仓储publicclassUserRepository:RepositoryBaseAppDbContext,User,string{publicUserRepository(AppDbContextdbContext):base(dbContext){}// 自定义查询方法publicasyncTaskListUserGetUsersByAge(intminAge,intmaxAge){returnawait_dbContext.Users.Where(uu.AgeminAgeu.AgemaxAge).ToListAsync();}}步骤4注册服务protectedoverridevoidConfigureServices(IServiceCollectionservices){services.AddDbContextAppDbContext();services.AddSingletonIRepositoryUser,string,UserRepository();}五、RepositoryBindable - 可绑定仓储5.1 概念RepositoryBindable是专为 WPF 数据绑定设计的仓储包装类它继承BindableBase支持属性变化通知自动管理数据集合提供增删改查的绑定命令5.2 使用示例publicclassUserRepositoryBindable:RepositoryBindableUser{// 可以重写 Where 方法进行过滤protectedoverrideboolWhere(Userentity){// 只显示年龄大于18的用户returnentity.Age18;}// 可以重写 CreateSelectBindable 自定义包装protectedoverrideSelectBindableUserCreateSelectBindable(Userentity){returnnewSelectBindableUser(entity);}}5.3 绑定到 UI!-- RepositoryBox 控件 --controls:RepositoryBoxRepository{Binding UserRepository}DataContext{Binding}/六、完整 CRUD 流程6.1 架构流程图┌─────────────────────────────────────────────────────────────────┐ │ 数据库层 │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Sqlite │ │ SQL Server │ │ Other │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ │ │ │ │ │ │ ▼ ▼ ▼ │ ├─────────────────────────────────────────────────────────────────┤ │ 仓储层 │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ RepositoryBaseTEntity, TPrimaryKey │ │ │ │ - GetList() / GetListAsync() │ │ │ │ - GetByID() / GetByIDAsync() │ │ │ │ - Insert() / InsertAsync() │ │ │ │ - Update() / UpdateAsync() │ │ │ │ - Delete() / DeleteAsync() │ │ │ │ - LoadPageList() │ │ │ └──────────────────────┬──────────────────────────────┘ │ │ │ │ │ ▼ │ ├─────────────────────────────────────────────────────────────────┤ │ RepositoryBindable层 │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ RepositoryBindableTEntity │ │ │ │ - Collection (ObservableCollection) │ │ │ │ - Add() / Remove() / RefreshData() │ │ │ │ - Commands (AddCommand, DeleteCommand, etc.) │ │ │ └──────────────────────┬──────────────────────────────┘ │ │ │ │ │ ▼ │ ├─────────────────────────────────────────────────────────────────┤ │ Presenter层 │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ RepositoryPresenterTEntity │ │ │ │ - 绑定 RepositoryBindable │ │ │ │ - 提供 UI 交互逻辑 │ │ │ └──────────────────────┬──────────────────────────────┘ │ │ │ │ │ ▼ │ ├─────────────────────────────────────────────────────────────────┤ │ UI层 │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ RepositoryBox / DataGridPresenter │ │ │ │ - 自动显示数据列表 │ │ │ │ - 提供增删改查按钮 │ │ │ └─────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘6.2 代码示例ViewModelpublicclassUserManagementViewModel:BindableBase{publicRepositoryBindableUserUserRepository{get;}publicUserManagementViewModel(RepositoryBindableUseruserRepository){UserRepositoryuserRepository;UserRepository.RefreshData();// 加载数据}// 新增用户publicICommandAddUserCommandnewRelayCommand((){UsernewUsernewUser{Name新用户,Emailnewexample.com,Age25};UserRepository.Add(newUser);});// 删除选中用户publicICommandDeleteSelectedCommandnewRelayCommand((){varselectedUserRepository.Collection.Where(xx.IsSelected).Select(xx.Entity).ToArray();UserRepository.Remove(selected);});}XAMLWindow.DataContextviewModels:UserManagementViewModel//Window.DataContextGrid!-- 工具栏 --StackPanelOrientationHorizontalMargin10ButtonCommand{Binding AddUserCommand}Content新增/ButtonCommand{Binding DeleteSelectedCommand}Content删除选中/ButtonCommand{Binding UserRepository.RefreshCommand}Content刷新//StackPanel!-- 数据列表 --controls:RepositoryBoxRepository{Binding UserRepository}Margin10//Grid七、数据库连接服务7.1 SqlServer 连接// 注册 SqlServer 服务services.AddSqlServer();// 配置连接字符串services.ConfigureISqlServerOption(options{options.ConnectionStringServerlocalhost;DatabaseMyDB;Trusted_ConnectionTrue;;});7.2 Sqlite 连接// 注册 Sqlite 服务services.AddSqlite();// 配置连接字符串services.ConfigureISqliteOption(options{options.ConnectionStringData Sourceapp.db;});八、最佳实践8.1 实体设计// ✅ 推荐继承合适的基类publicclassProduct:StringEntityBase{publicstringName{get;set;}publicdecimalPrice{get;set;}publicintStock{get;set;}// 添加索引属性[Index]publicstringCategory{get;set;}}8.2 仓储使用// ✅ 推荐通过构造函数注入publicclassProductService{privatereadonlyIRepositoryProduct,string_repository;publicProductService(IRepositoryProduct,stringrepository){_repositoryrepository;}publicasyncTaskListProductGetProductsByCategory(stringcategory){returnawait_repository.GetListAsync(pp.Categorycategory);}}8.3 事务处理// ✅ 推荐使用 SaveChanges 进行事务提交using(vartransactionawait_dbContext.Database.BeginTransactionAsync()){try{// 多个操作await_repository.InsertAsync(product1);await_repository.InsertAsync(product2);await_dbContext.SaveChangesAsync();awaittransaction.CommitAsync();}catch{awaittransaction.RollbackAsync();throw;}}九、总结数据库系统是 WPF-Control 的数据访问核心支持多数据库Sqlite、SQL Server仓储模式RepositoryBase 提供完整 CRUD可绑定仓储RepositoryBindable 适配 WPF 绑定快速构建RepositoryBox 一键生成管理页面使用流程定义实体类继承StringEntityBase或GuidEntityBase创建DbContext创建仓储类继承RepositoryBase注册服务使用RepositoryBindable绑定到 UI使用RepositoryBox显示数据这套体系可以极大简化数据库操作让开发者专注于业务逻辑。

相关文章:

数据库与仓储

数据库与仓储 位置:Source/DataBases 项目作用H.DataBases.Share数据库共享代码。H.DataBases.SqliteSqlite 支持。H.DataBases.SqlServerSQL Server 支持。 Repository 相关: H.Extensions.DataBase.Repository H.Presenters.Repository H.Controls.…...

化学合成革命:5分钟用AI完成复杂分子逆向合成路线设计

化学合成革命:5分钟用AI完成复杂分子逆向合成路线设计 【免费下载链接】aizynthfinder A tool for retrosynthetic planning 项目地址: https://gitcode.com/gh_mirrors/ai/aizynthfinder 你是否曾为设计一个复杂分子的合成路线而彻夜难眠?在传统…...

终极指南:如何用OpenHTMLtoPDF轻松生成专业级PDF文档

终极指南:如何用OpenHTMLtoPDF轻松生成专业级PDF文档 【免费下载链接】openhtmltopdf An HTML to PDF library for the JVM. Based on Flying Saucer and Apache PDF-BOX 2. With SVG image support. Now also with accessible PDF support (WCAG, Section 508, PDF…...

联想笔记本BIOS解锁神器:3分钟开启隐藏硬件性能

联想笔记本BIOS解锁神器:3分钟开启隐藏硬件性能 【免费下载链接】LEGION_Y7000Series_Insyde_Advanced_Settings_Tools 支持一键修改 Insyde BIOS 隐藏选项的小工具,例如关闭CFG LOCK、修改DVMT等等 项目地址: https://gitcode.com/gh_mirrors/le/LEGI…...

程序员会被产品经理替代吗?——当AI让“全栈”成为常态,我们的价值在哪里?

程序员会被产品经理替代吗?——当AI让“全栈”成为常态,我们的价值在哪里? 最近,V2EX上一个帖子引发了激烈讨论:随着AI能力的指数级增长,一个人就能完成从前需要整个团队才能做到的全栈开发。如果产品经理借…...

3个关键步骤:在macOS上制作Windows启动盘的完整指南

3个关键步骤:在macOS上制作Windows启动盘的完整指南 【免费下载链接】windiskwriter 🖥 Windows Bootable USB creator for macOS. 🛠 Patches Windows 11 to bypass TPM and Secure Boot requirements. 👾 UEFI & Legacy Sup…...

通过Taotoken聚合调用,在不同时段测试模型响应速度的观察

🚀 告别海外账号与网络限制!稳定直连全球优质大模型,限时半价接入中。 👉 点击领取海量免费额度 通过Taotoken聚合调用,在不同时段测试模型响应速度的观察 在构建依赖大模型能力的应用时,响应速度是一个直…...

Steam游戏时长与卡牌挂机:HourBoostr与SingleBoostr完整使用指南

Steam游戏时长与卡牌挂机:HourBoostr与SingleBoostr完整使用指南 【免费下载链接】HourBoostr Two programs for idling Steam game hours and trading cards 项目地址: https://gitcode.com/gh_mirrors/ho/HourBoostr Steam玩家都知道,解锁游戏交…...

别再瞎找了!2026年不容错过的专业AI论文软件

2026年AI论文写作工具已从“基础生成”升级为智能协同研究系统,核心评价维度包括文献真实性、格式合规性、长文本逻辑、查重降重、AIGC合规与多语言支持。本次测评覆盖6款主流工具,涵盖中文与英文场景、全流程与专项功能、免费与付费版本,让你…...

BilibiliDown音频提取终极指南:如何从B站视频中提取高质量音乐

BilibiliDown音频提取终极指南:如何从B站视频中提取高质量音乐 【免费下载链接】BilibiliDown (GUI-多平台支持) B站 哔哩哔哩 视频下载器。支持稍后再看、收藏夹、UP主视频批量下载|Bilibili Video Downloader 😳 项目地址: https://gitcode.com/gh_m…...

凡亿AD22--PCB设计课程项目总结及后续学习规划

一、本次PCB设计课程核心总结本次系列课程的核心定位是「PCB设计入门基础」,核心目标是帮助新手快速上手,搭建PCB设计的基础认知,整体围绕“工具操作基础知识点”两大核心展开,具体总结如下:1. 课程核心目标本次课程不…...

良心云用户如何快速接入Taotoken实现大模型API调用

🚀 告别海外账号与网络限制!稳定直连全球优质大模型,限时半价接入中。 👉 点击领取海量免费额度 良心云用户如何快速接入Taotoken实现大模型API调用 对于在良心云服务器上部署应用的开发者而言,将大模型能力集成到自己…...

如何快速掌握智能电源管理:macOS用户的完整配置指南

如何快速掌握智能电源管理:macOS用户的完整配置指南 【免费下载链接】SleeperX MacBook prevent idle/lid sleep! Hackintosh sleep on low battery capacity. 项目地址: https://gitcode.com/gh_mirrors/sl/SleeperX SleeperX是一款专为macOS用户设计的开源…...

8255与74LS273实现流水灯控制原理

箱图片和题目要求,这是一个经典的微机原理/接口技术实验。你需要构建一个包含输入(开关)、处理(8255读取)、输出(74LS273锁存驱动LED)的系统。由于我无法直接为你绘制CAD图纸,我为你…...

ElevenLabs芬兰语TTS深度评测:9大真实场景实测,准确率92.7% vs 传统引擎差距在哪?

更多请点击: https://intelliparadigm.com 第一章:ElevenLabs芬兰语TTS技术概览与评测背景 ElevenLabs 作为当前语音合成领域的领先平台,其多语言支持能力持续扩展,芬兰语(Finnish)于2023年第四季度正式纳…...

Solidity 知识点速记整理 - (2026年) (75 - 94)

文章目录前言Solidity 知识点速记整理 - (2026年) (75 - 94)前言 如果您觉得有用的话,记得给博主点个赞,评论,收藏一键三连啊,写作不易啊^ _ ^。   而且听说点赞的人每天的运气都不会太差,实在白嫖的话,那…...

视启未来[特殊字符]百度智能云:给大模型一双手,让AI真正触碰物理世界

如果说过去两年,大模型在数字世界里掀起了一场海啸;那么2026年,这场海啸正在以“具身智能”的形态,猛烈地拍击物理世界的海岸线。但这里却有一个“骨感”的现实:AI能写出拿普利策奖的文章,能画出媲美梵高的…...

从一次任务到一次进化:完整拆解 Skill 创建、复用、修补链路

点击上方 前端Q,关注公众号回复加群,加入前端Q技术交流群写到这一篇,第二章的拼图终于齐了。 前面四篇我把 Hermes 的自学习系统拆成了 4 个零件:Memory(记知识)、Skill(记做法)、Nu…...

BilibiliDown终极指南:5分钟掌握免费跨平台B站视频下载技巧

BilibiliDown终极指南:5分钟掌握免费跨平台B站视频下载技巧 【免费下载链接】BilibiliDown (GUI-多平台支持) B站 哔哩哔哩 视频下载器。支持稍后再看、收藏夹、UP主视频批量下载|Bilibili Video Downloader 😳 项目地址: https://gitcode.com/gh_mirr…...

BilibiliDown终极指南:5分钟掌握B站视频下载与音频提取

BilibiliDown终极指南:5分钟掌握B站视频下载与音频提取 【免费下载链接】BilibiliDown (GUI-多平台支持) B站 哔哩哔哩 视频下载器。支持稍后再看、收藏夹、UP主视频批量下载|Bilibili Video Downloader 😳 项目地址: https://gitcode.com/gh_mirrors/…...

iFakeLocation终极指南:3分钟实现iOS虚拟定位的完整教程

iFakeLocation终极指南:3分钟实现iOS虚拟定位的完整教程 【免费下载链接】iFakeLocation Simulate locations on iOS devices on Windows, Mac and Ubuntu. 项目地址: https://gitcode.com/gh_mirrors/if/iFakeLocation 想在iOS设备上轻松模拟任意位置吗&…...

3步拯救损坏视频!UNTRUNC开源工具让你的珍贵回忆重获新生

3步拯救损坏视频!UNTRUNC开源工具让你的珍贵回忆重获新生 【免费下载链接】untrunc Restore a damaged (truncated) mp4, m4v, mov, 3gp video. Provided you have a similar not broken video. 项目地址: https://gitcode.com/gh_mirrors/unt/untrunc 你是否…...

【ChatGPT】基于李群、李代数与螺旋理论的 Tricept 并联加工机器人控制系统软硬件架构深度拆解、信息图10张、爆炸图10张、C++代码框架

希望还能够有机会去研究他们(前提是能够遇到好领导)深度拆解...

Windows 11系统优化终极指南:用Win11Debloat免费让你的电脑飞起来

Windows 11系统优化终极指南:用Win11Debloat免费让你的电脑飞起来 【免费下载链接】Win11Debloat A simple, lightweight PowerShell script that allows you to remove pre-installed apps, disable telemetry, as well as perform various other changes to declu…...

大模型 API 中转站工程选型:token5u 接入与压测清单

工程项目里选 API 中转站,不能只看“能不能调通”。能调通只是第一步,后面还有协议兼容、模型路由、超时重试、流式输出、账单归因、Key 管理、企业结算和故障切换。本文按工程视角拆:行业风险、选型指标、推荐顺序、接入示例和上线前压测清单…...

ARM BRBE技术:硬件级控制流分析与优化

1. ARM分支记录缓冲区扩展(BRBE)技术概述在现代处理器架构中,控制流信息的捕获对于性能分析和代码优化至关重要。ARM分支记录缓冲区扩展(Branch Record Buffer Extension, BRBE)是ARMv8/v9架构中引入的一项硬件特性,它通过专用硬件机制记录程序执行过程中…...

Android截图限制终极解决方案:如何绕过FLAG_SECURE实现自由截屏

Android截图限制终极解决方案:如何绕过FLAG_SECURE实现自由截屏 【免费下载链接】DisableFlagSecure 项目地址: https://gitcode.com/gh_mirrors/dis/DisableFlagSecure 你是否曾在使用银行APP时想要截屏保存交易记录,却发现屏幕一片漆黑&#x…...

Windows 环境 OpenClaw 2.7.5 一键安装避坑指南

OpenClaw 一键安装包|可视化部署,简化环境配置流程✨适配系统:Windows10/11 64 位当前版本:v2.7.5(虾壳云版)✨核心优势:全程可视化操作,不用命令行、不用手动配置 Python/Node.js&a…...

【Midjourney宝丽来风格终极指南】:20年AI影像专家亲授3步调参法,97%用户忽略的胶片颗粒校准秘钥

更多请点击: https://codechina.net 第一章:宝丽来风格的视觉基因解码 宝丽来(Polaroid)成像并非仅关乎化学显影,其独特视觉语言根植于物理光学、色彩衰减模型与模拟噪声的协同作用。理解这一“视觉基因”&#xff0c…...

新手必看!OpenClaw 2.7.5 Windows 部署全流程

🦞 Windows 端 OpenClaw 完整部署实操教程 OpenClaw 一键安装包|可视化部署,简化环境配置流程✨适配系统:Windows10/11 64 位当前版本:v2.7.5(虾壳云版)✨核心优势:全程可视化操作&…...