我有一个使用EF6.1的WinForms应用程序。我在表单上自动填充了bindingsource和bindingnavigator。双击GridView中的客户会将我带到一个新表单,在该表单中我将此客户的详细信息显示为详细信息,并可选择添加新客户。 bindingsource只有一个项目和context.Local同样。单击导航器中的加号可以添加另一个客户,绑定源现在有两个项目可以跟踪上下文.Local仍然只有一个。我需要让我的上下文知道这个新记录,但我尝试过的所有内容似乎都为绑定源添加了另一条记录。这将在尝试保存时给出异常,因为未填充非可空列。代码是这样的:
private void frmCustomer_Load(object sender, EventArgs e)
{
using (context = new CarsEntities(Properties.Settings.Default.connectionString))
{
customer = context.Customers.Find(Id);
customerBindingSource.DataSource = customer;
}
}
private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
{
context.Customers.Local.Add((Customer)customerBindingSource.Current);
}
private void customerBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
foreach (var cust in context.Customers.Local.ToList())
{
if (cust.CustomerNo == null)
{
cust.CustomerNo = "8";//just for testing, will use a value from a sequence or something...
}
}
customerBindingSource.EndEdit();
context.SaveChanges();
}
}
答案 0 :(得分:0)
我认为您的问题是上下文加载DataSource和上下文以使SaveChanges指向内存中的不同上下文。根据朱莉娅·勒曼的编程实体框架一书,
你需要意识到只有上下文的事实 跟踪更改可以保存它们。您无法实例化新上下文并期望它将更改保存到您在表单中使用的实体。它不会对它们有任何了解。
因此,确保在调用SaveChanges时,使用与检索数据相同的上下文非常重要。
<强>解决方案强>
而不是 form_load 方法中的using (context = new CarsEntities(...))
,只需像context = new CarsEntities(...);
那样开启上下文。
然后,在form_closing方法中,放置context.dispose();
。
代码示例
private void frmCustomer_Load(object sender, EventArgs e)
{
context = new CarsEntities(Properties.Settings.Default.connectionString);
customer = context.Customers.Find(Id);
customerBindingSource.DataSource = customer;
}
private void frmCustomer_FormClosed(object sender, FormClosedEventArgs e)
{
context.dispose();
}
希望此解决方案能为您提供帮助。