Is this correct way of disposing and using
public partial class Form1 : Form
{
winappContext _context;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (_context = new winappContext())
{
_context = new winappContext();
var query = from c in _context.Customers
orderby c.CustomerName
select c;
this.customerBindingSource.DataSource = query.ToList();
}
....
or I need to call _context.Dispose() onFormClosing
Thanks
Neither. Assuming you don't need _context
to be a field (there's no indication that you do) you should make it a local variable:
private void Form1_Load(object sender, EventArgs e)
{
using (winappContext _context = new winappContext())
{
var query = from c in _context.Customers
orderby c.CustomerName
select c;
this.customerBindingSource.DataSource = query.ToList();
}
}
In general, it's a pain to have fields which implement IDisposable
- it's much cleaner if you can just dispose of resources within the same methods that they're acquired.
Also note that your original code creates two contexts:
using (_context = new winappContext())
{
_context = new winappContext();
...
}
That means the first one was being disposed of automatically, but the second wasn't. If you try to do this in a using
statement where you declare the variable as part of the introductory part of the statement, the variable is read-only so you can't make this mistake.
(You should also rename your winappContext
class to follow .NET naming conventions.)
See more on this question at Stackoverflow