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

问题描述 投票:5回答:2

我正在使用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正确“清理”连接,但我不知道如何实现。

有什么建议吗?

c# entity-framework-4 idisposable
2个回答
3
投票

不确定我是否真的明白这一点,但是您似乎实现了IDisposable,但是您需要调用Dispose或使用using

  using(UserRepository repo = new UserRepository())
  {
    // ...
  }

这在离开using块时调用Dispose并清理UserRepository。

有更多信息:


1
投票

StudentRepository还是UserRepository?而且,如果一个衍生自另一个,那么您就有问题了。

没有继承,您的StudentRepository实现是可以接受的。要完全正确,您应该通过将其声明为密封来确保:

public sealed  class StudentRepository : IDisposable
{
    ....
    public void Dispose()
    {
        db.Dispose();
    }
}

而且,正如@Stefan已经指出的,每次使用using() { }实例化StudentRepository时,都必须使用它。

© www.soinside.com 2019 - 2024. All rights reserved.