数据持久化
本文档引用的文件
- EfCoreMyEntityNameRepository.cs
- IMyEntityNameRepository.cs
- MyEntityName.cs
- CMSPluginEfCoreExtensions.MyEntityName.cs
- CMSPluginDbContext.cs
- CMSPluginEfCoreEntityExtensionMappings.cs
- CMSPluginDapperRepository.cs
- ICMSPluginDapperRepository.cs
- CMSPluginDbProperties.cs
- CMSPluginEntityFrameworkCoreModule.cs
- CMSPluginDbSchemaMigrator.cs
- MyEntityNameSpecification.cs
目录
引言
本项目采用领域驱动设计(DDD)架构,数据持久化机制以 Entity Framework Core(EF Core)为核心,结合 Dapper 实现高性能查询,支持 MySQL、PostgreSQL 和 SQL Server 多数据库。通过仓储模式(Repository Pattern)封装数据访问逻辑,确保领域层与基础设施层解耦。本文档全面分析该机制的实现细节。
仓储模式与接口契约
项目采用标准仓储模式,通过 IMyEntityNameRepository 接口定义数据访问契约,EfCoreMyEntityNameRepository 提供 EF Core 实现。接口定义了实体查询、计数、排序获取、名称唯一性校验等业务方法,确保领域服务通过抽象接口操作数据,不依赖具体实现。
IMyEntityNameRepository 继承自 IBasicRepository<MyEntityName, Guid>,扩展了 FindByNameAsync、NameExistAsync、GetMaxSortAsync 等业务专用方法,体现了领域驱动设计中“富仓储”的理念。
代码路径
IMyEntityNameRepository接口定义了所有查询契约EfCoreMyEntityNameRepository实现了这些契约
Section sources
EF Core 配置与实体映射
EF Core 的实体映射通过扩展方法 CMSPluginEfCoreExtensions.MyEntityName.cs 集中配置。ConfigureMyEntityName 方法在 ModelBuilder 上为 MyEntityName 实体定义了完整的数据库映射规则。
Diagram sources
表名与架构映射
实体映射到数据库表时,使用 CMSPluginDbProperties 中定义的前缀和架构:
b.ToTable((CMSPluginDbProperties.DbTablePrefix + "_MyEntityNames").ToLower(), CMSPluginDbProperties.DbSchema)
默认表名为 scms_myentitynames,位于默认架构下,支持通过配置修改。
属性配置
关键属性配置如下:
Code:最大长度由MyEntityNameConsts.MaxCodeLength定义,必填Name:最大长度由MyEntityNameConsts.MaxNameLength定义,必填Sort:整数类型,用于排序Remark:可选,最大长度由MyEntityNameConsts.MaxRemarkLength定义IsDisabled:可空布尔值,表示是否禁用
索引配置
为 Name 字段创建了唯一索引,确保名称的唯一性约束:
b.HasIndex(u => u.Name);
关系定义
当前 MyEntityName 实体未定义导航属性,为聚合根(Aggregate Root),其内部关系由领域逻辑维护,符合 DDD 原则。
Section sources
数据库上下文管理
项目定义了 ICMSPluginDbContext 接口作为数据库上下文契约,继承自 IEfCoreDbContext。具体的上下文实现(如 CMSPluginDbContext)在各数据库提供程序项目中(MySQL、PostgreSQL、SqlServer)提供。
Diagram sources
OnModelCreating 方法中调用 builder.ConfigureMyEntityName() 注册实体配置,并通过 builder.TryConfigureObjectExtensions<CMSPluginDbContext>() 应用对象扩展,支持模块化配置。
数据库连接字符串名称通过 [ConnectionStringName] 特性指定为 MyPluginName,定义在 CMSPluginDbProperties.ConnectionStringName。
Section sources