我有一个get方法,我对要返回的对象的某些数组属性进行了一些过滤:
public async Task<WorkflowStepDto> GetCurrentWorkflowStep(string entity, string status, string clientId = null)
{
var workflowStep = await _workflowStepRepository.GetAll().Include("WorkflowEntity")
.Include("WorkflowStepActions").Include("WorkflowStepConfigurations")
.FirstOrDefaultAsync(s => s.Name == status && s.WorkflowEntity.Name == entity);
var workflowRoles = User.Claims.Where(c => c.Type == "workflowRole").Select(c => c.Value).ToArray();
workflowStep.WorkflowStepActions =
workflowStep.WorkflowStepActions
.Where(s => (workflowRoles.Contains(s.WorkflowRole) ||
(workflowRoles.Length == 0 && string.IsNullOrEmpty(s.WorkflowRole)) ||
s.WorkflowRole == "*")).OrderBy(a => a.Priority).ToList();
workflowStep.WorkflowStepConfigurations = workflowStep.WorkflowStepConfigurations
.Where(c => workflowRoles.Contains(c.WorkflowStepRoleId) ||
(workflowRoles.Length == 0 && string.IsNullOrEmpty(c.WorkflowStepRoleId)))
.OrderBy(c => c.Priority).Take(1).ToList();
return workflowStep.MapTo<WorkflowStepDto>();
}
例如,需要过滤掉属性WorkflowStepActions
以仅显示用户有权访问的操作,WorkflowStepConfigurations
也是如此。
问题是UnitOfWork
模式。即使这是GET
方法而且我不想保存任何数据,但在方法结束时,UnitOfWork会将更改保存到数据库,删除已过滤的WorkflowStepActions
在当前的电话中。
我尝试使用[UnitOfWork(IsDisabled=false)]
完全禁用UnitOfWork,但后来我收到一条错误消息,说明因为它已被处理而无法访问存储库。
有没有办法AcceptChanges
到UnitOfWork,或者让它自动停止保存更改?
答案 0 :(得分:1)
使用此方法非常重要(在appservice,domainservice,custom class等中)。
假设您在域服务中使用它
您必须将[UnitOfWork]属性添加到方法并将方法设为虚拟。
[UnitOfWork]
public virtual async Task<WorkflowStepDto> GetCurrentWorkflowStep(string entity, string status, string clientId = null)
{
}
如果您想以异步方式手动保存更改。您可以在任何应用程序服务中使用以下代码。
await CurrentUnitOfWork.SaveChangesAsync();
如果您想开始新的工作单元,可以使用此
//inject IUnitOfWorkManager to your class in constructor method.
private readonly IUnitOfWorkManager _unitOfWorkManager;
public async Task<WorkflowStepDto> GetCurrentWorkflowStep(...)
{
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
//You can save changes in any step of code to get some new inserted record's id... This is not required if you don't have such insertions.
await _unitOfWorkManager.Current.SaveChangesAsync();
//You have to apply Complete method in the end.
await uow.CompleteAsync();
}
}
要获取更多信息,请阅读文档 - &gt; https://aspnetboilerplate.com/Pages/Documents/Unit-Of-Work
答案 1 :(得分:0)
尝试此解决方法,但在这种情况下,GetCurrentWorkflowStep
应该是独立的,即不会被另一个代码隐式调用:
public IUnitOfWorkManager _unitOfWorkManager {get; set;}
[UnitOfWork(IsDisabled = true)]
public async Task<WorkflowStepDto> GetCurrentWorkflowStep(...)
{
using (var unitOfWork = _unitOfWorkManager.Begin())
{
//your code....
}
}