0

I have an MVC 4 application, and while registering I have come across issue where data is saved in usertable but not in other table i.e user_detail etc.., to avoid that I tried to use tranascationScope well it worked for the registemethod as below.

 public ActionResult Register(model model)
 {
     using (var scope = new TransactionScope())
     {
         WebSecurity.CreateUserAndAccount(model.RegUserName, randomPassword,....)
         // other table commit.
         // other table commit.
     }
 }

Once after register a call is being made to any action method as below

 private void AuthenticateUser(string userName)
 {
      int userId = WebSecurity.GetUserId(userName);
 }

The current TransactionScope is already complete.

I am getting the above error and the connection is a single and using EF5.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Harry
  • 338
  • 1
  • 6
  • 19
  • 1
    you should indent your code for make it more readable... – Mauro Bilotti Jul 14 '14 at 14:56
  • Where are you getting the error? What is the *actual* code you're using? I can assure you that your *comments* aren't generating errors, but the actual code you're not showing us very well could be. – David Jul 14 '14 at 14:59
  • 1
    Show us your code where you initialize the DBContext, I have a feeling your reusing the same instance for every db call. – Tamim Al Manaseer Jul 14 '14 at 15:00
  • Well I am using structure Map .NET IoC containers and for everytable there is a separate object and the same is being used for all actions in the controller for every db operation. Just wanted to know If this doable or I should take any other approach. – Harry Jul 14 '14 at 17:00

1 Answers1

1

I'm not an expert on StructureMap, but from the error I guess, you're creating a single instance (Singleton) from the DBContext. which will give you this error.

Once you start a transaction, the context will be aware of it and handle your work, but after the transaction is complete you can't resuse the same dbcontext instance, you need to create a new one.

A preferred method in web apps is to use a Context Per Request. Here is an example I found on SO.

Community
  • 1
  • 1
Tamim Al Manaseer
  • 3,554
  • 3
  • 24
  • 33