Search code examples
asp.netentity-frameworkarchitecturedata-access-layer

Is it possible to create Attribute for controller, which executes all query into db via one transaction?


I mean next situation. This example a little bit ugly, but it shows what exactly I want.

[MyAttribute]
public MyController
{
     [Post]
     public void CoolStuff(int id, Item item)
     {
          User user = _userRepository.Get(id);

          Bucket bucket = _bucketRepository.Get(user.bucketId);

          bucket.Add(item);

          _bucketRepository.Save(bucket);
     }
}

There are 3 queres into db. I want that [MyAttribute] collects these queries in transaction and executes. Do you have any ideas?


Solution

  • Take a look at the ActionFilterAttribute. You can derive your custom attribute from ActionFilterAttribute and override two methods:

    OnActionExecuting - to open a transaction
    OnActionExecuted - to comit or rollback the transaction

    Hope it helps!