我使用 WinForms 和 Entity Framework 6。我有一个:
public class ApplicationDbContext : DbContext {
public DbSet<Person> People{ get; set; }
}
每个 Person
都有属性:Id
、Name
、LastName
、Age
.
在 Form
中,我想在 ListBox
中显示所有 People
并且我想保留此 的内容>ListBox
与数据库同步。
如何将 BindingList bindingList
绑定(bind)到 ApplicationDBContext 上下文
,或者反过来?
点评:这是SSCCE。
最佳答案
您可以使用 ToBindingList()
获取 BindingList<Person>
的扩展方法你需要一个DataSource
在你的ListBox
:
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
执行相应的添加/删除操作.
关于c# - 我可以将 DbSet 和 BindingList 绑定(bind)在一起以在 ListBox 中显示数据库内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831396/