///// <summary> ///// 包含 ///// </summary> ///// <typeparam name="T">源类型</typeparam> ///// <param name="items">IEnumerable扩展</param> ///// <param name="value">值</param> ///// <returns></returns> //public static bool Contains2<T>(this IEnumerable<T> items, T value) { // if (items.IsNull()) throw new ArgumentNullException("items"); // ICollection<T> c = items as ICollection<T>; // if (c.IsNotNull()) return c.Contains(value); // throw new NotImplementedException(); //} ///// <summary> ///// 构造器 速度慢 反射 ///// </summary> ///// <typeparam name="T">源类型</typeparam> ///// <param name="Parameters">IEnumerable扩展</param> ///// <param name="Properties"></param> ///// <returns></returns> //public static T Constructor<T>(this IEnumerable<object> Parameters, IDictionary<string, object> Properties) where T : class { // Type ttype = typeof(T); // T obj = (T)Activator.CreateInstance(typeof(T), Parameters); // foreach (string key in Properties.Keys) { // PropertyInfo prop = ttype.GetProperty(key); // if (prop.IsNotNull()) prop.SetValue(obj, Properties[key], null); // } // return obj; //} /// <summary> /// Flatten /// </summary> /// <typeparam name="T">源类型</typeparam> /// <param name="inputs">IEnumerable扩展</param> /// <param name="enumerate">Func委托函数</param> /// <returns></returns> public static IEnumerable <T> Flatten <T>(this IEnumerable <T> inputs, Func <T, IEnumerable <T> > enumerate) { if (inputs.IsNotNull()) { var stack = new Stack <T>(inputs); while (stack.Count > 0) { var current = stack.Pop(); if (current.IsNull()) { continue; } yield return(current); var enumerable = enumerate.IsNotNull() ? enumerate(current) : null; if (enumerable.IsNotNull()) { foreach (var child in enumerable) { stack.Push(child); } } } } }
/// <summary> /// 异步添加单条实体 /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual async Task <OperationResponse> InsertAsync(TEntity entity, Func <TEntity, Task> checkFunc = null, Func <TEntity, TEntity, Task <TEntity> > insertFunc = null, Func <TEntity, TEntity> completeFunc = null) { entity.NotNull(nameof(entity)); try { if (checkFunc.IsNotNull()) { await checkFunc(entity); } if (!insertFunc.IsNull()) { entity = await insertFunc(entity, entity); } //entity = CheckInsert(entity); await _dbSet.AddAsync(entity); if (completeFunc.IsNotNull()) { entity = completeFunc(entity); } int count = await _dbContext.SaveChangesAsync(); return(new OperationResponse(count > 0 ? "添加成功" : "操作没有引发任何变化", count > 0 ? OperationResponseType.Success : OperationResponseType.NoChanged)); } catch (AppException e) { return(new OperationResponse(e.Message, OperationResponseType.Error)); } catch (Exception ex) { return(new OperationResponse(ex.Message, OperationResponseType.Error)); } }
/// <summary> /// 以异步DTO插入实体 /// </summary> /// <typeparam name="TInputDto">添加DTO类型</typeparam> /// <param name="dto">添加DTO</param> /// <param name="checkFunc">添加信息合法性检查委托</param> /// <param name="insertFunc">由DTO到实体的转换委托</param> /// <returns>操作结果</returns> public virtual async Task <OperationResponse> InsertAsync <TInputDto>(TInputDto dto, Func <TInputDto, Task> checkFunc = null, Func <TInputDto, TEntity, Task <TEntity> > insertFunc = null, Func <TEntity, TInputDto> completeFunc = null) where TInputDto : IInputDto <Tkey> { dto.NotNull(nameof(dto)); try { if (checkFunc.IsNotNull()) { await checkFunc(dto); } TEntity entity = dto.MapTo <TEntity>(); if (!insertFunc.IsNull()) { entity = await insertFunc(dto, entity); } entity = CheckInsert(entity); await _dbSet.AddAsync(entity); if (completeFunc.IsNotNull()) { dto = completeFunc(entity); } int count = await _dbContext.SaveChangesAsync(); return(new OperationResponse(count > 0 ? ResultMessage.InsertSuccess : ResultMessage.NoChangeInOperation, count > 0 ? OperationEnumType.Success : OperationEnumType.NoChanged)); } catch (SuktAppException e) { return(new OperationResponse(e.Message, OperationEnumType.Error)); } catch (Exception ex) { return(new OperationResponse(ex.Message, OperationEnumType.Error)); } }
public T SingleOrDefault(Expression <Func <T, bool> > predicate = null, Func <IQueryable <T>, IOrderedQueryable <T> > orderBy = null, Func <IQueryable <T>, IIncludableQueryable <T, object> > include = null, bool enableTracking = true, bool ignoreQueryFilters = false) { IQueryable <T> queryable = DbSet; if (!enableTracking) { queryable = queryable.AsNoTracking(); } if (predicate.IsNotNull()) { queryable = queryable.Where(predicate !); } if (!ignoreQueryFilters) { queryable = queryable.IgnoreQueryFilters(); } if (include.IsNotNull()) { queryable = include !(queryable); } if (orderBy.IsNotNull()) { queryable = orderBy !(queryable); } return(queryable.FirstOrDefault()); }
/// <summary> /// Executes a stored procedure and returns the result as a List<TSource> /// </summary> /// <typeparam name="TSource">The Model for the returned Dataset</typeparam> /// <param name="storedProcedure">Name of the stored procedure</param> /// <param name="replaceResourceKeys">If true replaces all the tokens {#ResourceKey} with the relative resource value from the files under the Resources folder</param> /// <param name="overwriteResultFunction">Delegate function used to overwrite/manipulate the data returned from the Stored Procedure</param> /// <param name="commandTimeout">Sets the wait time before terminating the attempt to execute a command and generating an error. Use 0 to set infinite timeout.</param> /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param> /// <returns>Results as a List<TSource></returns> public static List <TSource> ExecListProc <TSource>(string storedProcedure, bool replaceResourceKeys = true, Func <List <TSource>, List <TSource> > overwriteResultFunction = null, int commandTimeout = 30, params object[] args) { List <TSource> result = null; using (AdoHelper db = new AdoHelper(commandTimeout)) { var returnValue = db.CreateParamReturnValue("returnValue"); List <object> argsList = args.ToList(); argsList.Add(returnValue); using (DataSet ds = db.ExecDataSetProc(storedProcedure, argsList.ToArray())) { if (db.GetParamReturnValue(returnValue) == 0) { if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { if (overwriteResultFunction.IsNotNull()) { result = overwriteResultFunction(ds.Tables[0].ToList <TSource>(replaceResourceKeys)); } else { result = ds.Tables[0].ToList <TSource>(replaceResourceKeys); } } } else { throw new Exception("The stored procedure " + storedProcedure + " returned the error code " + db.GetParamReturnValue(returnValue)); } } } return(result); }
public Task <IPaginate <TResult> > SelectAsync <TResult>(Expression <Func <T, TResult> > selector, Expression <Func <T, bool> > predicate = null, Func <IQueryable <T>, IOrderedQueryable <T> > orderBy = null, Func <IQueryable <T>, IIncludableQueryable <T, object> > include = null, int index = 0, int size = 20, bool enableTracking = true, CancellationToken cancellationToken = default, bool ignoreQueryFilters = false) where TResult : class { IQueryable <T> queryable = _dbSet; if (!enableTracking) { queryable = queryable.AsNoTracking(); } if (!predicate.IsNotNull()) { queryable = queryable.Where(predicate !); } if (!ignoreQueryFilters) { queryable = queryable.IgnoreQueryFilters(); } if (include.IsNotNull()) { queryable = include !(queryable); } if (orderBy.IsNotNull()) { queryable = orderBy !(queryable); } return(queryable.Select(selector).ToPaginateAsync(index, size, cancellationToken: cancellationToken)); }
public static List <Type> ExportedTypes(this IEnumerable <Assembly> assemblies, Func <IEnumerable <Type>, IEnumerable <Type> > filterTypes = null, Action <Exception> exceptionAction = null) { assemblies.NotEmpty(nameof(assemblies)); var allTypes = new List <Type>(); foreach (var assembly in assemblies) { try { allTypes.AddRange(assembly.GetExportedTypes()); } catch (NotSupportedException notSupported) { exceptionAction?.Invoke(notSupported); continue; } catch (FileNotFoundException fileNotFound) { exceptionAction?.Invoke(fileNotFound); continue; } } if (filterTypes.IsNotNull()) { allTypes = filterTypes.Invoke(allTypes).ToList(); } return(allTypes); }
/// <summary> /// 以异步DTO更新实体 /// </summary> /// <typeparam name="TInputDto">更新DTO类型</typeparam> /// <param name="dto">更新DTO</param> /// <param name="checkFunc">添加信息合法性检查委托</param> /// <param name="updateFunc">由DTO到实体的转换委托</param> /// <returns>操作结果</returns> public virtual async Task <OperationResponse> UpdateAsync <TInputDto>(TInputDto dto, Func <TInputDto, TEntity, Task> checkFunc = null, Func <TInputDto, TEntity, Task <TEntity> > updateFunc = null) where TInputDto : class, IInputDto <Tkey>, new() { dto.NotNull(nameof(dto)); try { TEntity entity = await this.GetByIdAsync(dto.Id); if (entity.IsNull()) { return(new OperationResponse($"该{dto.Id}键的数据不存在", OperationEnumType.QueryNull)); } if (checkFunc.IsNotNull()) { await checkFunc(dto, entity); } entity = dto.MapTo(entity); if (!updateFunc.IsNull()) { entity = await updateFunc(dto, entity); } entity = CheckUpdate(entity); _dbSet.Update(entity); int count = await _dbContext.SaveChangesAsync(); return(new OperationResponse(count > 0 ? ResultMessage.UpdateSuccess : ResultMessage.NoChangeInOperation, count > 0 ? OperationEnumType.Success : OperationEnumType.NoChanged)); } catch (SuktAppException e) { return(new OperationResponse(e.Message, OperationEnumType.Error)); } catch (Exception ex) { throw ex; } }
public IPaginate <TResult> Select <TSource, TResult>(Expression <Func <T, TResult> > selector, Expression <Func <T, bool> > predicate = null, Func <IQueryable <T>, IOrderedQueryable <T> > orderBy = null, Func <IQueryable <T>, IIncludableQueryable <T, object> > include = null, int index = 0, int size = 20, bool enableTracking = true) where TResult : class { IQueryable <T> queryable = DbSet; if (!enableTracking) { queryable = queryable.AsNoTracking(); } if (predicate.IsNotNull()) { queryable = queryable.Where(predicate !); } if (include.IsNotNull()) { queryable = include !(queryable); } if (orderBy.IsNotNull()) { queryable = orderBy !(queryable); } return(queryable.Select(selector).AsEnumerable().ToPaginate(index, size)); }
private void HandleRunQuery <TNextActionType>(Func <IQueryableRepository <TEntity>, TNextActionType> queryableRepositoryOperation, Action <TNextActionType> operationToExecuteBeforeNextOperation) { CheckForObjectAlreadyDisposedOrNot(typeof(QueryableRepository <TEntity>).FullName); ContractUtility.Requires <ArgumentNullException>(queryableRepositoryOperation.IsNotNull(), "queryableRepositoryOperation instance cannot be null"); Action operation = () => { TNextActionType queryReturnValue = _unitOfWork.IsNull() ? ExceptionHandlingUtility.HandleExceptionWithNullCheck( () => queryableRepositoryOperation(this), _exceptionHandler) : queryableRepositoryOperation(this); //TODO - proper exception handling compensating handler needs to be here if (operationToExecuteBeforeNextOperation.IsNotNull()) { operationToExecuteBeforeNextOperation(queryReturnValue); } }; if (_unitOfWork.IsNotNull()) { _unitOfWork.AddOperation(operation); } else { operation(); } }
/// <summary> /// 将结果字符串转换为指定类型 /// </summary> private HttpResponse <TResult> ConvertTo(HttpResponse response) { if (_convertAction.IsNotNull()) { return(response.To(_convertAction(response.Data))); } return(response.To <TResult>()); }
public string RaiseInterceptionAspect(Func <List <AspectJoinPoints>, string> func, List <AspectJoinPoints> args) { if (func.IsNotNull()) { return(func(args)); } return(AspectJoinPoints.NoEvent.ToString()); }
public ServiceClientFactory(Func <IAsyncServiceClient> getAsyncServiceClient, Func <IServiceClient> getServiceClient) { getServiceClient.IsNotNull(nameof(getServiceClient)); getAsyncServiceClient.IsNotNull(nameof(getAsyncServiceClient)); _getAsyncServiceClient = getAsyncServiceClient; _getServiceClient = getServiceClient; }
public List <AspectJoinPoints> RaiseInterceptionAspect(Func <List <AspectJoinPoints> > func) { if (func.IsNotNull()) { return(func()); } return(new List <AspectJoinPoints>()); }
public static X509Certificate2 GetCertificate(StoreName storeName, StoreLocation storeLocation, Func<X509Certificate2, bool> certFinder) { DBC.True(certFinder.IsNotNull(), () => "Must supply a certificate finder"); X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2 cert = store.Certificates.Cast<X509Certificate2>().FirstOrDefault(certFinder); store.Close(); DBC.False(cert.IsNull(), () => $"No certificate matching the request found in {storeLocation}/{storeName}"); return cert; }
public string RaiseInterceptionAspect(Func <List <AspectJoinPoints>, List <AspectJoinPoints>, List <AspectJoinPoints>, List <AspectJoinPoints>, List <AspectJoinPoints>, List <AspectJoinPoints>, List <AspectJoinPoints>, string> func, List <AspectJoinPoints> arg1, List <AspectJoinPoints> arg2, List <AspectJoinPoints> arg3, List <AspectJoinPoints> arg4, List <AspectJoinPoints> arg5, List <AspectJoinPoints> arg6, List <AspectJoinPoints> arg7) { if (func.IsNotNull()) { return(func(arg1, arg2, arg3, arg4, arg5, arg6, arg7)); } return(AspectJoinPoints.NoEvent.ToString()); }
/// <summary> /// 转换为可分页集合(注:需要对查询接口进行排序操作,否则 LINQ 会抛出未排序异常)。 /// </summary> /// <typeparam name="TEntity">指定的实体类型。</typeparam> /// <param name="query">给定的 <see cref="IQueryable{TEntity}"/>。</param> /// <param name="orderedFactory">给定的排序方式。</param> /// <param name="index">给定的页索引。</param> /// <param name="size">给定的页大小。</param> /// <returns>返回 <see cref="IPageable{TEntity}"/>。</returns> public static IPageable <TEntity> AsPagingByIndex <TEntity>(this IQueryable <TEntity> query, Func <IQueryable <TEntity>, IOrderedQueryable <TEntity> > orderedFactory, int?index, int?size) where TEntity : class { if (orderedFactory.IsNotNull()) { query = orderedFactory.Invoke(query); } return(query.AsPaging(paging => paging.ComputeByIndex(index, size))); }
/// <summary> /// Executes a stored procedure while caches and returns the result as a List<TSource> /// </summary> /// <typeparam name="TSource">The Model for the returned Dataset</typeparam> /// <param name="storedProcedure">Name of the stored procedure</param> /// <param name="force">If true reloads the data from the database</param> /// <param name="replaceResourceKeys">If true replaces all the tokens {#ResourceKey} with the relative resource value from the files under the Resources folder</param> /// <param name="overwriteResultFunction">Delegate function used to overwrite/manipulate the data returned from the Stored Procedure</param> /// <param name="cacheKey">If null or empty it will be equal to storedProcedure</param> /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param> /// <returns>Results as a List<TSource></returns> public static List <TSource> ExecCachedListProc <TSource>(string storedProcedure, bool force = false, bool replaceResourceKeys = true, Func <List <TSource>, List <TSource> > overwriteResultFunction = null, string cacheKey = null, params object[] args) { HttpContext context = HttpContext.Current; if (cacheKey.IsEmptyOrWhiteSpace()) { cacheKey = storedProcedure; } if (force || context.Cache[cacheKey] == null) //Double check locking { lock (ThisLock) { if (force || context.Cache[cacheKey] == null) //Double check locking { using (AdoHelper db = new AdoHelper()) { var returnValue = db.CreateParamReturnValue("returnValue"); List <object> argsList = args.ToList(); argsList.Add(returnValue); using (DataSet ds = db.ExecDataSetProc(storedProcedure, argsList.ToArray())) { if (db.GetParamReturnValue(returnValue) == 0) { if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { if (overwriteResultFunction.IsNotNull()) { context.Cache.Insert(cacheKey, overwriteResultFunction(ds.Tables[0].ToList <TSource>(replaceResourceKeys))); } else { context.Cache.Insert(cacheKey, ds.Tables[0].ToList <TSource>(replaceResourceKeys)); } } else { context.Cache.Remove(cacheKey); } } else { context.Cache.Remove(cacheKey); throw new Exception("The stored procedure " + storedProcedure + " returned the error code " + db.GetParamReturnValue(returnValue)); } } } } } } return(context.Cache[cacheKey] as List <TSource>); }
/// <summary> /// 转换为可分页集合(注:需要对查询接口进行排序操作,否则执行 LINQ 会抛出未排序异常)。 /// </summary> /// <typeparam name="TEntity">指定的实体类型。</typeparam> /// <param name="queryable">给定的 <see cref="IQueryable{TEntity}"/>。</param> /// <param name="orderedFactory">给定的排序方式。</param> /// <param name="skip">给定的跳过条数。</param> /// <param name="take">给定的获取条数。</param> /// <returns>返回 <see cref="IPageable{TEntity}"/>。</returns> public static IPageable <TEntity> AsPagingBySkip <TEntity>(this IQueryable <TEntity> queryable, Func <IQueryable <TEntity>, IOrderedQueryable <TEntity> > orderedFactory, int?skip, int?take) where TEntity : class { if (orderedFactory.IsNotNull()) { queryable = orderedFactory.Invoke(queryable); } return(queryable.AsPaging(paging => paging.ComputeBySkip(skip, take))); }
public static TResult GuardedExecution <TResult>(this object src, Func <TResult> f, Func <Exception, TResult> onException = null) { TResult result = default(TResult); try { result = f(); } catch (Exception ex) { onException.IsNotNull(() => result = onException(ex)); } return(result); }
/// <summary> /// Get page result from page result dto. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> /// <param name="dto"></param> /// <param name="selector"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// <paramref name="dto"/> is null /// -or- /// <paramref name="selector"/> is null /// </exception> public static PageResult <U> ToPageResult <T, U>(this PageResultDto <T> dto, Func <T, U> selector) where T : class, new() { dto.IsNotNull(nameof(dto)); selector.IsNotNull(nameof(selector)); return(new PageResult <U>( dto.pageNo, dto.pages, dto.total, dto.list?.Select(selector).ToList() ?? new List <U>() )); }
private void ThrowExceptionForRollbackCheck() { if (!_isProcessDataMethodExecutedAtleastOnce) { _isProcessDataMethodExecutedAtleastOnce = true; } else { if (_throwExceptionActionToTestRollback.IsNotNull()) { _throwExceptionActionToTestRollback(); } } }
internal static R Otherwise <R>(Func <Unit, R> otherwise, Func <Unit, Exception> otherwiseThrow) { return(otherwise.AsMaybe().Match( _ => { if (otherwiseThrow.IsNotNull()) { throw otherwiseThrow(Unit.Value); } throw UnhandledException; }, o => o(Unit.Value) )); }
public IPaginate <T> Select(Expression <Func <T, bool> > predicate = null, Func <IQueryable <T>, IOrderedQueryable <T> > orderBy = null, Func <IQueryable <T>, IIncludableQueryable <T, object> > include = null, int index = 0, int size = 20) { IQueryable <T> queryable = DbSet; if (predicate.IsNotNull()) { queryable = queryable.Where(predicate !); } if (orderBy.IsNotNull()) { queryable = include !(queryable); } if (orderBy.IsNotNull()) { queryable = orderBy !(queryable); } return(queryable.ToPaginate(index, size)); }
public T SingleOrDefault(Expression <Func <T, bool> > predicate = null, Func <IQueryable <T>, IOrderedQueryable <T> > orderBy = null, Func <IQueryable <T>, IIncludableQueryable <T, object> > include = null) { IQueryable <T> queryable = DbSet; if (predicate.IsNotNull()) { queryable = queryable.Where(predicate !); } if (orderBy.IsNotNull()) { queryable = include !(queryable); } if (orderBy.IsNotNull()) { queryable = orderBy !(queryable); } return(queryable.SingleOrDefault()); }
private async Task HandleExceptionWithThrowCondition(Exception ex, Func <CancellationToken, Task> onExceptionCompensatingHandler, CancellationToken onExceptionCompensatingHandlerCancellationToken) { await _logger.LogExceptionAsync(ex); if (onExceptionCompensatingHandler.IsNotNull() && !_areFallbackPoliciesAlreadyHandled) { _areFallbackPoliciesAlreadyHandled = true; await onExceptionCompensatingHandler(onExceptionCompensatingHandlerCancellationToken); } if (_shouldThrowOnException) { throw new Exception("Check Inner Exception", ex); } }
public T Get <T>(string key, CacheTimeSpan timeSpan, Func <T> getItem) { var cacheItem = CacheStore.Get(key); if (cacheItem.IsNull() && getItem.IsNotNull()) { cacheItem = getItem(); if (cacheItem != null) { Put(key, timeSpan, cacheItem); } } return((T)cacheItem); }
private PolicyWrap GetPolicyWrapWithProperFallbackActionSetForFallbackPoliciesAsync(Exception ex, Func <CancellationToken, Task> fallbackAction) { IEnumerable <IPolicy> policiesForCurrentException = GetPoliciesForException(ex); if (fallbackAction.IsNotNull()) { _areFallbackPoliciesAlreadyHandled = true; policiesForCurrentException.Where(x => x is IFallbackActionPolicy).Select(x => x as IFallbackActionPolicy).ForEach(x => x.SetFallbackAction(fallbackAction)); } else { _areFallbackPoliciesAlreadyHandled = false; policiesForCurrentException = policiesForCurrentException.Where(x => !(x is IFallbackActionPolicy)); } return(_policyWrapForAsyncOperationsFunc(policiesForCurrentException)); }
public virtual async Task <bool> TryAddOrUpdateAsync(Expression <Func <TEntity, bool> > predicate, Func <Task <TEntity> > addFunc, Func <TEntity, Task <bool> > isUpdatedFunc = null, Action <EntityEntry <TEntity> > addedPostAction = null, Action <EntityEntry <TEntity> > updatedPostAction = null, Action <EntityEntry <TEntity> > addedOrUpdatedPostAction = null, CancellationToken cancellationToken = default) { // From Database var entity = await DbSet.FirstOrDefaultAsync(predicate, cancellationToken).ConfigureAwait(); if (entity.IsNull()) { EntityEntry <TEntity> added; // From Local Cache entity = DbSet.Local.FirstOrDefault(predicate.Compile()); if (entity.IsNull()) { entity = await addFunc.Invoke().ConfigureAwait(); added = await DbSet.AddAsync(entity, cancellationToken).ConfigureAwait(); } else { // 默认使用附加,保存更改核心会自行根据情况重置状态 added = DbSet.Attach(entity); } addedPostAction?.Invoke(added); addedOrUpdatedPostAction?.Invoke(added); return(true); } if (isUpdatedFunc.IsNotNull() && await isUpdatedFunc.Invoke(entity).ConfigureAwait()) { var updated = DbSet.Update(entity); updatedPostAction?.Invoke(updated); addedOrUpdatedPostAction?.Invoke(updated); return(true); } return(false); }
private void ThrowExceptionForRollbackCheck(bool isForAsync) { if ((isForAsync && _shouldThrowForCommitAsync) || (!isForAsync && !_shouldThrowForCommitAsync)) { if (!_isProcessDataMethodExecutedAtleastOnce) { _isProcessDataMethodExecutedAtleastOnce = true; } else { if (_throwExceptionActionToTestRollback.IsNotNull()) { _throwExceptionActionToTestRollback(); } } } }
public virtual bool TryAddOrUpdate(Expression <Func <TEntity, bool> > predicate, Func <TEntity> addFunc, Func <TEntity, bool> isUpdatedFunc = null, Action <EntityEntry <TEntity> > addedPostAction = null, Action <EntityEntry <TEntity> > updatedPostAction = null, Action <EntityEntry <TEntity> > addedOrUpdatedPostAction = null) { // From Database var entity = DbSet.FirstOrDefault(predicate); if (entity.IsNull()) { EntityEntry <TEntity> added; // From Local Cache entity = DbSet.Local.FirstOrDefault(predicate.Compile()); if (entity.IsNull()) { entity = addFunc.Invoke(); added = DbSet.Add(entity); } else { // 默认使用附加,保存更改核心会自行根据情况重置状态 added = DbSet.Attach(entity); } addedPostAction?.Invoke(added); addedOrUpdatedPostAction?.Invoke(added); return(true); } if (isUpdatedFunc.IsNotNull() && isUpdatedFunc.Invoke(entity)) { var updated = DbSet.Update(entity); updatedPostAction?.Invoke(updated); addedOrUpdatedPostAction?.Invoke(updated); return(true); } return(false); }
protected ActionResult ValidateAndSendCommand(Command command, Func<ActionResult> successFunc, Func<ActionResult> failFunc, Func<ActionResult> validationFailFunc = null, Func<bool> preCondition = null, Func<ActionResult> preConditionResult = null) { if (preCondition.IsNull() || preCondition()) { if (ModelState.IsValid) { _commandBus.Send(command); return successFunc(); } else if(validationFailFunc.IsNotNull()) { return validationFailFunc(); } } else if (preConditionResult.IsNotNull()) { return preConditionResult(); } return failFunc(); }