是否可以将 DbSet 和 BindingList 绑定在一起以在 ListBox 中显示数据库内容

本文关键字:ListBox 显示 数据库 绑定 DbSet 是否 BindingList 在一起 | 更新日期: 2023-09-27 17:56:13

我使用 WinForms 和 Entity Framework 6。我有一个:

  public class ApplicationDbContext : DbContext {
        public DbSet<Person> People{ get; set; }
  }

每个Person都有属性:IdNameLastNameAge

Form中,我想显示ListBox中的所有People,并希望使此ListBox的内容与数据库同步。

如何将BindingList bindingList绑定到ApplicationDBContext context,或者相反?

评论:这是SSCCE。

是否可以将 DbSet 和 BindingList 绑定在一起以在 ListBox 中显示数据库内容

您可以使用 ToBindingList() 扩展方法来获取所需的BindingList<Person>作为ListBox中的DataSource

public partial class YourForm : Form
{
    private YourContext context=new YourContext();
    public BindingList<Person> BindingList { get; set; }

    private void YourForm_Load(object sender, EventArgs e)
    {
        context.People.Load();
        this.listBox1.DataSource= BindingList= context.People.Local.ToBindingList();
        this.listBox1.DisplayMember = "Name";
    }
    //Button for save new changes
    private void SaveChangesButton_Click(object sender, EventArgs e)
    {
        context.SaveChanges();
    }
    //Disposing the context before close the form
    private void YourForm_FormClosing(object sender, FormClosingEventArgs e) 
    { 
        context.Dispose(); 
    } 
}

DbSet中添加或删除对象时,也会在BindingList中添加或删除该对象。在BindingList中添加或删除也将在DbSet上执行相应的添加/删除。