我使用 Entity Framework 4 和 MSSQL 在我的 Windows 窗体应用程序上存储和访问数据。
这是我用来访问数据的示例类:
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();
}
}
这是我如何使用它的示例。
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();
}
}
有人建议我使用 IDisposable 来正确地“清理”连接,但我不知道如何实现它。
有什么建议吗?
最佳答案
不确定我是否真的明白了,但你似乎实现了 IDisposable
,但你需要调用 Dispose
或使用 using
:
using(UserRepository repo = new UserRepository())
{
// ...
}
这会在离开 using block 时调用 Dispose 并清理 UserRepository。
还有一些信息:
关于c# - 我将如何在这种情况下实现 IDisposable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4985146/