Dpz.Core.Entity.Base
dpz.core 系统实体基类库,提供所有实体类型的基础定义、接口、转换器和辅助功能。
目标框架: .NET 11.0
📋 主要特性
核心功能
- ✅ 实体基类: 提供统一的实体基类定义,支持 MongoDB ObjectId
- ✅ 索引定义: 声明式的 MongoDB 索引定义支持
- ✅ 表达式树查询: 基于特性的动态查询条件生成器
- ✅ 对象映射: 基于 Mapster 的对象映射配置支持
- ✅ 类型转换: ObjectId、Boolean 等类型的序列化转换器
- ✅ 响应结果: 统一的 API 响应结果封装
- ✅ 公共结构: 常用的公共数据结构定义
🔧 技术栈
- .NET: 10.0
- MongoDB: MongoDB.Bson
- 对象映射: Mapster, Mapster.DependencyInjection
- 依赖: Dpz.Core.EnumLibrary
💡 使用示例
1. 实体基类
BaseEntity
最基础的实体类,包含 MongoDB ObjectId 主键:
using Dpz.Core.Entity.Base;
public class Article : BaseEntity
{
public string Title { get; set; }
public string Content { get; set; }
}
// ObjectId 会自动通过 ObjectIdConverter 进行 JSON 序列化转换
BasicInformationEntity
扩展的基础实体类,包含创建时间和更新时间:
public class BlogPost : BasicInformationEntity
{
public string Title { get; set; }
public string Content { get; set; }
// 自动包含:
// - Id (ObjectId)
// - CreateTime (DateTime)
// - LastUpdateTime (DateTime)
}
2. MongoDB 索引定义
实现 IIndexedEntity<T> 接口来声明实体的索引:
public class Article : BasicInformationEntity, IIndexedEntity<Article>
{
public string Title { get; set; }
public string Category { get; set; }
public DateTime PublishDate { get; set; }
public static IReadOnlyList<EntityIndexDefinition> GetIndexDefinitions()
{
return new[]
{
// 单字段索引
new EntityIndexDefinition
{
IndexName = "idx_title",
Fields = new[]
{
new EntityIndexField
{
FieldName = nameof(Title),
SortDirection = IndexSortDirection.Ascending
}
}
},
// 复合索引
new EntityIndexDefinition
{
IndexName = "idx_category_date",
Fields = new[]
{
new EntityIndexField
{
FieldName = nameof(Category),
SortDirection = IndexSortDirection.Ascending
},
new EntityIndexField
{
FieldName = nameof(PublishDate),
SortDirection = IndexSortDirection.Descending
}
},
IsUnique = false
}
};
}
}
3. 表达式树查询
使用 QueryFilterAttribute 特性自动生成查询条件:
public class ArticleQueryDto
{
// 等于查询
[QueryFilter(FilterCondition.HasValue, Comparison = Comparison.Equal)]
public string? Category { get; set; }
// 包含查询(模糊搜索)
[QueryFilter(FilterCondition.HasValue, Comparison = Comparison.Contains)]
public string? Title { get; set; }
// 大于等于查询
[QueryFilter(FilterCondition.HasValue, Comparison = Comparison.GreaterThanOrEqual)]
public DateTime? StartDate { get; set; }
// 小于等于查询
[QueryFilter(FilterCondition.HasValue, Comparison = Comparison.LessThanOrEqual)]
public DateTime? EndDate { get; set; }
// 忽略此属性
[IgnoreProperty]
public int PageIndex { get; set; }
}
// 使用方法
var queryDto = new ArticleQueryDto
{
Category = "Tech",
Title = "MongoDB",
StartDate = DateTime.Today.AddDays(-30)
};
// 生成表达式树
Expression<Func<Article, bool>> filter = queryDto.BuildFilter<Article, ArticleQueryDto>();
// 在 MongoDB 查询中使用
var results = await repository.SearchFor(filter).ToListAsync();
支持的查询条件:
FilterCondition.HasValue- 属性有值时生成条件FilterCondition.NotNull- 属性不为 null 时生成条件FilterCondition.EqualValue- 属性等于指定值时生成条件
支持的比较方式:
Comparison.Equal- 等于Comparison.NotEqual- 不等于Comparison.Contains- 包含(字符串)Comparison.GreaterThan- 大于Comparison.GreaterThanOrEqual- 大于等于Comparison.LessThan- 小于Comparison.LessThanOrEqual- 小于等于Comparison.In- 在集合中
4. Mapster 对象映射
实现 IHaveCustomMapping 接口来自定义映射规则:
public class ArticleDto : IHaveCustomMapping
{
public string Id { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public static void CreateMappings(TypeAdapterConfig cfg)
{
cfg.NewConfig<Article, ArticleDto>()
.Map(dest => dest.Id, src => src.Id.ToString())
.Map(dest => dest.Summary, src => src.Content.Substring(0, 100));
}
}
5. 响应结果封装
使用 ResponseResult 统一 API 响应格式:
// 成功响应
return ResponseResult.ToSuccess();
return ResponseResult.ToSuccess("操作成功");
// 失败响应
return ResponseResult.ToFail("操作失败");
return ResponseResult.ToFail("参数错误", code: 400);
// 带数据的响应
return ResponseResult<ArticleDto>.ToSuccess(articleDto);
return ResponseResult<List<ArticleDto>>.ToSuccess(articles);
// 带分页的响应
return ResponseResult<PagedResult<ArticleDto>>.ToSuccess(new PagedResult<ArticleDto>
{
Data = articles,
Total = totalCount,
PageIndex = pageIndex,
PageSize = pageSize
});
6. 用户信息
UserInfo 类用于存储当前用户的基本信息:
var userInfo = new UserInfo
{
Id = "user123",
Name = "张三",
Enable = true,
LastAccessTime = DateTime.Now,
Signature = "Hello World",
Role = UserRole.Member
};
📚 主要组件说明
实体基类
| 类名 | 说明 | 包含属性 |
|---|---|---|
IBaseEntity | 实体基础接口 | 无 |
BaseEntity | 基础实体类 | Id (ObjectId) |
BasicInformationEntity | 扩展实体类 | Id, CreateTime, LastUpdateTime |
类型转换器
| 类名 | 说明 | 用途 |
|---|---|---|
ObjectIdConverter | ObjectId 转换器 | MongoDB ObjectId 与字符串的 JSON 序列化转换 |
BooleanConverter | 布尔值转换器 | 布尔值的特殊序列化处理 |
索引定义
| 类名 | 说明 |
|---|---|
IIndexedEntity<T> | 索引实体接口 |
EntityIndexDefinition | 索引定义类 |
EntityIndexField | 索引字段定义 |
IndexKeyType | 索引键类型枚举 |
IndexSortDirection | 索引排序方向枚举 |
表达式树查询
| 类名 | 说明 |
|---|---|
GenerateConditionFilter | 条件过滤表达式树生成器 |
QueryFilterAttribute | 查询过滤特性 |
IgnorePropertyAttribute | 忽略属性特性 |
FilterCondition | 过滤条件枚举 |
Comparison | 比较方式枚举 |
公共结构
| 类名 | 说明 |
|---|---|
FileAddress | 文件地址结构 |
InterceptRule | 拦截规则结构 |
AnonymousNames | 匿名用户名称生成器 |
Adjectives | 形容词词库 |
📦 安装
项目引用
<ItemGroup>
<ProjectReference Include="..\Dpz.Core.Entity.Base\Dpz.Core.Entity.Base.csproj" />
</ItemGroup>
⚠️ 注意事项
- ObjectId 序列化: 实体的
Id属性使用ObjectIdConverter进行 JSON 序列化,会自动转换为字符串格式 - DateTime 序列化:
BasicInformationEntity的时间字段使用BsonDateTimeOptions设置为本地时间 - 索引创建: 实现
IIndexedEntity<T>接口后,需要在应用启动时调用索引创建逻辑 - 表达式树缓存:
GenerateConditionFilter内部使用ConcurrentDictionary缓存属性信息,提升性能 - Mapster 配置: 实现
IHaveCustomMapping的类需要在应用启动时注册映射配置
🔗 相关项目
- Dpz.Core.EnumLibrary - 枚举类型库
- Dpz.Core.MongodbAccess - MongoDB 数据访问层
- Dpz.Core.Infrastructure - 基础设施组件
📄 许可证
Copyright © dpangzi
🔄 设计模式
1. 表达式树缓存模式
使用 ConcurrentDictionary 缓存属性反射信息,避免重复反射:
private static readonly ConcurrentDictionary<Type, PropertyInfo[]> PropertyCache = new();
2. 静态抽象成员模式
利用 C# 11 的静态抽象成员特性,定义接口级别的工厂方法:
public interface IIndexedEntity<T>
{
static abstract IReadOnlyList<EntityIndexDefinition> GetIndexDefinitions();
}
3. 特性驱动模式
通过特性标记实现声明式编程,自动生成查询条件:
[QueryFilter(FilterCondition.HasValue, Comparison = Comparison.Equal)]
public string? Category { get; set; }
💡 最佳实践
- 继承 BasicInformationEntity:对于需要记录时间的实体,推荐继承
BasicInformationEntity - 定义索引:为常用查询字段定义索引,提升查询性能
- 使用 DTO:使用 DTO 类定义查询参数,利用表达式树查询功能
- 统一响应:API 接口统一使用
ResponseResult返回结果 - 映射配置:复杂的对象映射使用
IHaveCustomMapping自定义配置
评论加载中...