I like to wrap my data access in using statements to make myself feel good about garbage collection. I am running Visual Studio 2013 Preview and targeting .NET 4.5. I have an ApiController called WordsController as such:
public class WordsController : ApiController
{
// GET api/<controller>
public IEnumerable<Keyword> Get()
{
using (TestDataContext dc = new TestDataContext())
{
return dc.Keywords;
}
}
}
I get an error telling me that the datacontext has been disposed before accessing the data.
Changing the code to this works:
public class WordsController : ApiController
{
// GET api/<controller>
public IEnumerable<Keyword> Get()
{
TestDataContext dc = new TestDataContext();
return dc.Keywords;
}
}
Why does this work when not using
the DataContext?
db
on every function inside your class so why not just initialize with the class itself? That's how everyone is doing it anyway..Dispose
on yourIDisposable
objectdc
, so that is not good practice. If the garbage collector happens (for reasons we can't control) to not collectdc
soon, it could be problematic.