How to use a dbcontext in a static class? (ObjectDisposedException)
Yeah, so, although the extensions are new and shiny to you, that doesn't mean you should use them for everything. First, extensions should have a logical connection to the type they're operating on. For example, if you have a string
, something like ToUpper()
makes sense as an extension because it modifies and returns a string. Something like what you're trying to do: just using the value of the reference to return a completely foreign type is a violation of the extension pattern.
Second, an extension should not interact with something like a database. In particular here, the static nature of an extension is completely incompatible with the concept of a EF context object. The only way you could even get it to work is to actually new up a context each time the extension is called, inside the extension. That's both a great way to screw up the EF object tracking stuff and a great way to leak memory.
Long and short, don't do this.
If you're just trying to factor out this code, you have better options. For example, you can actually just add methods directly to your context.
public class ApplicationDbContext : DbContext
{
...
public bool HasDota2Account(string id)
{
return Dota2Accounts.Any(m => m.ApplicationUserId == id);
}
}
Then, in your controller, you can simply do:
var hasDota2Account = context.HasDota2Account(User.Identity.GetUserId());
Never declare DbContext as static, it will cause all sorts of trouble, and not refresh the data, so you will be getting old data from a query. An option is to instantiate it inside the static method every time you use it, like this:
public static MyClass Example
{
public static bool MyStaticMethod(long id)
{
MyDBContext db = new MyDBContext();
//use db context now....
}
}