Entity Framework Core 1.0 unit of work with Asp.Net Core middleware or Mvc filter

前端 未结 3 1423
一整个雨季
一整个雨季 2020-12-14 19:44

I am using EF Core 1.0 (previously known ad EF7) and ASP.NET Core 1.0 (previously known as ASP.NET 5) for a RESTful API.

I\'d like to have some unit of work scoped t

3条回答
  •  时光说笑
    2020-12-14 20:01

    I am also facing the same issue and not sure which approach to follow. One of the approach that I used is as follow:

    public class UnitOfWorkFilter : ActionFilterAttribute
    {
        private readonly AppDbContext _dbContext;
    
        public UnitOfWorkFilter(AppDbContext dbContext,)
        {
            _dbContext = dbContext;
        }
    
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            if (!context.HttpContext.Request.Method.Equals("Post", StringComparison.OrdinalIgnoreCase))
                return;
            if (context.Exception == null && context.ModelState.IsValid)
            {
                _dbContext.Database.CommitTransaction();
            }
            else
            {
                _dbContext.Database.RollbackTransaction();
            }
        }
    
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.HttpContext.Request.Method.Equals("Post", StringComparison.OrdinalIgnoreCase))
                return;
            _dbContext.Database.BeginTransaction();
        }
    }
    

提交回复
热议问题