ABP VNext项目里,如何用FreeSql和SqlSugar替换掉EFCore?保姆级配置流程分享

ABP VNext项目里,如何用FreeSql和SqlSugar替换掉EFCore?保姆级配置流程分享 ABP VNext项目中用FreeSql和SqlSugar替代EFCore的实战指南对于熟悉ABP框架但希望摆脱EFCore束缚的.NET开发者来说FreeSql和SqlSugar这两个更符合国内开发习惯的ORM无疑是不错的选择。本文将带你从零开始一步步完成在ABP VNext项目中集成这两种ORM的全过程。1. 为什么要在ABP VNext中替换EFCoreABP框架默认集成EFCore作为ORM解决方案这确实为开发者提供了开箱即用的便利。但实际开发中我们可能会遇到以下情况性能考量某些场景下FreeSql和SqlSugar展现出更好的查询性能语法习惯国内开发者更熟悉类似SqlSugar的链式调用风格功能需求需要FreeSql强大的多数据库支持特性项目迁移已有项目使用这些ORM需要与ABP框架集成关键对比特性EFCoreFreeSqlSqlSugar学习曲线中等低低性能中等高高多数据库支持有限全面中等社区生态国际主流国内活跃国内活跃LINQ支持完善完善完善2. 项目准备与环境配置在开始替换前我们需要准备一个基础的ABP VNext项目。如果你已有项目可以跳过此步骤。# 创建新ABP项目 abp new MyProject -t app -u mvc --mobile none --database-provider none安装必要的NuGet包!-- FreeSql相关 -- PackageReference IncludeFreeSql.Provider.MySql Version3.2.800 / PackageReference IncludeFreeSql.DbContext Version3.2.800 / !-- SqlSugar相关 -- PackageReference IncludeSqlSugarCore Version5.1.4.63 /3. FreeSql集成详细步骤3.1 创建FreeSql模块在ABP中模块化是核心设计理念。我们需要创建一个专门的模块来配置FreeSql[DependsOn(typeof(AbpDddDomainModule))] public class MyProjectFreeSqlModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { var configuration context.Services.GetConfiguration(); var connectionString configuration.GetConnectionString(Default); var freeSql new FreeSqlBuilder() .UseConnectionString(DataType.MySql, connectionString) .UseAutoSyncStructure(false) // 建议关闭自动同步结构 .Build(); context.Services.AddSingletonIFreeSql(freeSql); // 配置FreeSql仓储 context.Services.AddAbpDbContextMyProjectDbContext(options { options.AddDefaultRepositories(includeAllEntities: true); }); } }3.2 实现FreeSql仓储基类创建基础仓储类供领域服务继承使用public abstract class FreeSqlRepositoryTEntity : DomainService where TEntity : class, IEntity { protected IFreeSql FreeSql LazyServiceProvider.LazyGetRequiredServiceIFreeSql(); public virtual async TaskTEntity GetAsync(Guid id) { return await FreeSql.SelectTEntity().Where(x x.Id id).FirstAsync(); } public virtual async TaskListTEntity GetListAsync() { return await FreeSql.SelectTEntity().ToListAsync(); } // 其他常用CRUD方法... }4. SqlSugar集成详细步骤4.1 创建SqlSugar模块与FreeSql类似我们需要为SqlSugar创建专门的模块[DependsOn(typeof(AbpDddDomainModule))] public class MyProjectSqlSugarModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { var configuration context.Services.GetConfiguration(); var connectionString configuration.GetConnectionString(Default); context.Services.AddSingletonISqlSugarClient(serviceProvider { var sqlSugar new SqlSugarScope(new ConnectionConfig() { DbType DbType.MySql, ConnectionString connectionString, IsAutoCloseConnection true, ConfigureExternalServices new ConfigureExternalServices() { EntityService (property, column) { // 处理实体特性映射 var attributes property.GetCustomAttributes(true); if (attributes.Any(it it is KeyAttribute)) { column.IsPrimarykey true; } } } }); return sqlSugar; }); } }4.2 实现SqlSugar仓储基类public abstract class SqlSugarRepositoryTEntity : DomainService where TEntity : class, new() { protected ISqlSugarClient Db LazyServiceProvider.LazyGetRequiredServiceISqlSugarClient(); public virtual async TaskTEntity GetAsync(Guid id) { return await Db.QueryableTEntity().InSingleAsync(id); } public virtual async TaskListTEntity GetListAsync() { return await Db.QueryableTEntity().ToListAsync(); } // 其他常用CRUD方法... }5. 实际应用与最佳实践5.1 在应用服务中使用自定义仓储public class ProductAppService : ApplicationService { private readonly IRepositoryProduct, Guid _productRepository; private readonly IFreeSql _freeSql; private readonly ISqlSugarClient _sqlSugar; public ProductAppService( IRepositoryProduct, Guid productRepository, IFreeSql freeSql, ISqlSugarClient sqlSugar) { _productRepository productRepository; _freeSql freeSql; _sqlSugar sqlSugar; } public async TaskListProductDto GetProductsWithFreeSql() { var products await _freeSql.SelectProduct() .Where(p p.IsActive) .ToListAsync(); return ObjectMapper.MapListProduct, ListProductDto(products); } public async TaskListProductDto GetProductsWithSqlSugar() { var products await _sqlSugar.QueryableProduct() .Where(p p.IsActive) .ToListAsync(); return ObjectMapper.MapListProduct, ListProductDto(products); } }5.2 性能优化建议连接管理FreeSql默认使用连接池SqlSugar配置IsAutoCloseConnection为true批量操作// FreeSql批量插入 await _freeSql.Insert(products).ExecuteAffrowsAsync(); // SqlSugar批量插入 await _sqlSugar.Insertable(products).ExecuteCommandAsync();复杂查询优化// FreeSql多表查询 var result await _freeSql.SelectT1, T2, T3() .LeftJoin((a, b, c) a.Id b.T1Id) .Where((a, b, c) a.Status 1) .ToListAsync(); // SqlSugar多表查询 var result await _sqlSugar.QueryableT1() .LeftJoinT2((a, b) a.Id b.T1Id) .Where(a a.Status 1) .ToListAsync();6. 常见问题与解决方案6.1 事务处理FreeSql事务using (var uow _freeSql.CreateUnitOfWork()) { try { await _freeSql.Insert(entity1).ExecuteAffrowsAsync(); await _freeSql.Update(entity2).ExecuteAffrowsAsync(); uow.Commit(); } catch { uow.Rollback(); throw; } }SqlSugar事务await _sqlSugar.Ado.UseTranAsync(async () { await _sqlSugar.Insertable(entity1).ExecuteCommandAsync(); await _sqlSugar.Updateable(entity2).ExecuteCommandAsync(); });6.2 与ABP原有仓储的兼容性建议采取以下策略对于简单CRUD继续使用ABP的标准仓储对于复杂查询使用FreeSql/SqlSugar直接操作通过依赖注入同时获取两种方式public class HybridService : DomainService { private readonly IRepositoryProduct, Guid _abpRepository; private readonly IFreeSql _freeSql; public HybridService( IRepositoryProduct, Guid abpRepository, IFreeSql freeSql) { _abpRepository abpRepository; _freeSql freeSql; } public async Task HybridMethod() { // 使用ABP仓储进行简单操作 await _abpRepository.InsertAsync(new Product()); // 使用FreeSql进行复杂查询 var complexData await _freeSql.SelectProduct() .Where(...) .GroupBy(...) .ToListAsync(); } }在实际项目中根据团队技术栈和项目需求选择合适的ORM方案。FreeSql适合需要多数据库支持的项目而SqlSugar则以其简洁的API和出色的性能受到许多开发者的青睐。无论选择哪种方案ABP框架的模块化设计都能很好地支持这些第三方ORM的集成。