I'm using Entity Framework 4 along with MSSQL to store and access data on my Windows Forms application.
Here is an example class I use to access data:
public class StudentRepository : IDisposable
{
ColegioDBEntities db = new ColegioDBEntities();
public IQueryable<Student> FindAllStudents()
{
return db.Students;
}
public Student FindStudent(int id)
{
return db.Students.SingleOrDefault(c => c.StudentId == id);
}
public void Add(Student Student)
{
db.AddToStudents(Student);
}
public void Save()
{
db.SaveChanges();
}
public void Dispose()
{
db.Dispose();
}
}
And here's an example of how I use it.
private void btnLogin_Click(object sender, EventArgs e)
{
UserRepository repo = new UserRepository();
var result = repo.FindAllUsers().Where(u => u.Username == txtUsername.Text && u.Password == txtPassword.Text);
if (result.Count() > 0)
{
MainForm form = new MainForm(txtUsername.Text);
form.Show();
this.Hide();
}
else
{
MessageBox.Show("Usuario y/o contraseña incorrecta.",
"Acceso Denegado",
MessageBoxButtons.OK,
MessageBoxIcon.Stop,
MessageBoxDefaultButton.Button1);
txtUsername.Focus();
txtPassword.Focus();
}
}
Someone suggested that I use IDisposable to properly "clean up" the connection, but I don't know how to implement this.
Any suggestions?
Not sure if I really got the point, but you seem to implement IDisposable
, but you need to call Dispose
or use using
:
using(UserRepository repo = new UserRepository())
{
// ...
}
This calls Dispose when leaving the using block and cleans up the UserRepository.
There is some more information: