我的数据库中有一个 Student
表和一堆其他表,名为 University
,我使用 Entity Framework 在我的 winforms 应用程序中连接到它。
我从 Entity Framework 模型中的 Student
表创建了一个 DataSource
。
然后我将 DataSource
拖到我的表单上。(见下图)
我知道如何将 student
表的记录(这里只是我的数据库中的一条记录)填充到 DataGridView
中,使用这段代码没有问题:
//An instance of my EFModel
Oublic UniversityEntities UE = new UniversityEntities();
private void Form1_Load_1(object sender, EventArgs e)
{
studentBindingSource.DataSource = UE.Students.ToList();
}
但我想使用 BindingNavigator
从数据库中插入/更新/删除记录,考虑到我使用的是 Entity Framework,我不知道这怎么可能。
例如,我尝试在编辑一行后保存更改,但没有成功:
private void studentBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
UE.SaveChanges();
}
最佳答案
我知道这是一个旧线程,但我遇到了同样的问题,但在这里没有答案。
这一行打破了 DataSource 与上下文的连接:
studentBindingSource.DataSource = UE.Students.ToList();
改为:
studentBindingSource.DataSource = UE.Students;
但它抛出异常,所以我只是将它绑定(bind)到本地数据:
studentBindingSource.DataSource = UE.Students.Local;
绑定(bind)前还需要确保本地数据已经填满。
关于c# - 如何通过 BindingNavigator 插入、更新和删除 DataGridView 的记录到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20858367/