c# - 我将如何在这种情况下实现 IDisposable?

标签 c# entity-framework-4 idisposable

我使用 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/

相关文章:

entity-framework - EF4 - 数据未刷新/更新

c# - 如果类继承自 IDisposable(或任何),则接口(interface)从 IDisposable(或任何)继承是好的/必要的吗?

c# - 找出加在一起时哪些字节等于另一个字节

c# - Fluent NHibernate映射: QuantLib.日期和Mysql的日期

c# - EF 代码第一个 : Defining foreign keys

c# - EF4审计多对多关系的变化

c# - 在 C# 中将 'using' 与线程实用程序一起使用 - 何时调用 Dispose?

powershell - 如何确保在停止信号时对高级函数的局部变量调用 Dispose()?

c# - 在没有 Thread.Sleep(300) 的情况下,如何在此类中获得真正的随机性?

c# - 通过约定的多列唯一约束 FluentNHibernate 自动映射