@@ -23,11 +23,17 @@ public sealed partial class MongoDbService
2323 /// <typeparam name="TState">缓存状态的类型,必须是BaseCacheState的子类,并具有无参数构造函数。</typeparam>
2424 /// <param name="id">要加载的缓存状态的ID。</param>
2525 /// <param name="filter">可选的过滤器,用于进一步限制查询结果的条件。</param>
26+ /// <param name="isCreateIfNotExists">是否创建不存在的文档</param>
2627 /// <returns>加载的缓存状态,如果未找到则返回新创建的状态。</returns>
27- public async Task < TState > FindAsync < TState > ( long id , Expression < Func < TState , bool > > filter = null ) where TState : BaseCacheState , new ( )
28+ public async Task < TState > FindAsync < TState > ( long id , Expression < Func < TState , bool > > filter = null , bool isCreateIfNotExists = true ) where TState : BaseCacheState , new ( )
2829 {
2930 var findExpression = GetDefaultFindExpression ( filter ) ;
3031 var state = await _mongoDbContext . Find < TState > ( ) . Match ( findExpression ) . OneAsync ( id ) ;
32+ if ( ! isCreateIfNotExists )
33+ {
34+ return state ;
35+ }
36+
3137 var isNew = state == null ;
3238
3339 if ( state == null )
@@ -38,6 +44,7 @@ public sealed partial class MongoDbService
3844
3945 // 调用后处理方法以加载状态的其他数据
4046 state . LoadFromDbPostHandler ( isNew ) ;
47+
4148 return state ;
4249 }
4350
@@ -47,11 +54,18 @@ public sealed partial class MongoDbService
4754 /// </summary>
4855 /// <typeparam name="TState">缓存状态的类型,必须是BaseCacheState的子类,并具有无参数构造函数。</typeparam>
4956 /// <param name="filter">查询条件,用于限制查找的结果。</param>
57+ /// <param name="isCreateIfNotExists">是否创建不存在的文档</param>
5058 /// <returns>满足条件的缓存状态,如果未找到则返回新创建的状态。</returns>
51- public async Task < TState > FindAsync < TState > ( Expression < Func < TState , bool > > filter ) where TState : BaseCacheState , new ( )
59+ public async Task < TState > FindAsync < TState > ( Expression < Func < TState , bool > > filter , bool isCreateIfNotExists = true ) where TState : BaseCacheState , new ( )
5260 {
5361 var findExpression = GetDefaultFindExpression ( filter ) ;
5462 var state = await _mongoDbContext . Queryable < TState > ( ) . Where ( findExpression ) . SingleOrDefaultAsync ( ) ;
63+
64+ if ( ! isCreateIfNotExists )
65+ {
66+ return state ;
67+ }
68+
5569 var isNew = state == null ;
5670
5771 if ( state == null )
@@ -62,6 +76,7 @@ public sealed partial class MongoDbService
6276
6377 // 调用后处理方法以加载状态的其他数据
6478 state . LoadFromDbPostHandler ( isNew ) ;
79+
6580 return state ;
6681 }
6782
0 commit comments