I often have static classes which uses the DataContext
somehow, and they all make a new DataContext
, but often I already have one instantiated elsewhere, so why not use that?
public static bool SignIn(string email, string password, DataContext db = null)
{
bool disposeDb = false;
if (db == null)
{
disposeDb = true;
db = new DataContext();
}
//Sign In stuff, or any other stuff...
if (disposeDb) db.Dispose();
}
But is there a cool trick to do this, or am I just coding it wrong? Or is it ok?
Update
The DataContext
is not expensive to instantiate. I guess I just leave it be.
But here is another example:
public static User GetUser(DataContext db = null)
{
if (HttpContext.Current.Request.Cookies["Id"] == null)
{
return null;
}
else
{
bool disposeDb = false;
if (db == null)
{
disposeDb = true;
db = new DataContext();
}
int id = Convert.ToInt32(HttpContext.Current.Request.Cookies["Id"].Value);
string cookieKey = HttpContext.Current.Request.Cookies["CookieKey"].Value;
User user = db.Users.FirstOrDefault(x => x.Id == id && x.CookieKey == cookieKey);
if (disposeDb) db.Dispose();
return user;
}
}
This is again nice because if I already have a context, I can provide it, and then I won't have to attach the entity (User) to another context if I want to modify it:
User user = MyClass.GetUser(db);
user.Email = "asdsasd";
db.SaveChanges();
How can I improve it? Or is it okay?
Update 2
The DataContext
should only be instantiated once per page request. And here is a neat way to do it, that actually allows me to access it even from static methods.
db
is not passed in be reference, it should be disposed automatically as it falls out of scope when the function exists. Why do you sometimes pass in an instantiatedDataContext
, and why do you want it to auto-dispose. Is it good or bad? Well, it depends. What are you trying to do? – Leonid Dec 2 '12 at 0:01DataContext
? If it is expensive, then perhaps you create t once and hold on to it. Does the library provide the connection pooling for you? I do not like your original code (nothing personal), but I cannot tell you exactly how to make it better because I do not see examples of how you are using it. It is weird to me that theDataContext
may or may not be already created. What control that? – Leonid Dec 2 '12 at 0:26