I have an Action that requires authentication. The action method creates some records with foreign keys using Linq to SQL. When the user calls the action and is logged in the method works without a problem. When the user is not logged in, MVC redirects them to the login page with the returnUrl parameter. After a successful login the action method is executed, but this time it throws the following error:
An attempt has been made to Attach or
Add an entity that is not new, perhaps
having been loaded from another
DataContext. This is not supported.
All queries are using the same datacontext and on the same request.
The code goes through the same execution path in both scenarios so I trully don’t understand what’s going on and why? Does anyone have any idea why this would happen?
I found the problem!
The action method was retrieving some entities using the global datacontext and then it called the User property of the base controller which gets the User object from session. Since this was the first time it was retrieving it after the user authenticated it was calling my GetCustomerWithCustomerInfo() method. That method was indeed instantiating the global datacontext again (for some reason) and hence it made all the previous retrieved entities orphans, which explains why I was getting the error above. It also explains why I wasn’t getting the error when the user was previously logged in. The User object was being retrieved from session and therefore the context was not being instantiated.
I didn’t want to include code because it was too complicated and I couldn’t narrow it down.
I guess next time I get that error I should really trust it.
Now I need to find out why the GetCustomerWithCustomerInfo creating a new datacontext.