views:

71

answers:

1

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?

A: 

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.

Jonas Stawski
Sigh, we were supposed to magically divine your issue without seeing your code?
jfar
@jfar, Programming is not only about code. I spent many hours debugging this issue and couldn't find a difference and hence that's why I thought it wasn't relevant. I was looking for guidance like the static comment. Anyway, next time you might want to try and help rather than being sarcastic
Jonas Stawski