Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用WinForms中的详细信息创建实体框架和bindingNavigator.AddNew_C#_Entity Framework_Data Binding - Fatal编程技术网

C# 使用WinForms中的详细信息创建实体框架和bindingNavigator.AddNew

C# 使用WinForms中的详细信息创建实体框架和bindingNavigator.AddNew,c#,entity-framework,data-binding,C#,Entity Framework,Data Binding,我有一个WinForms应用程序,使用EF6.1。我在表单上自动填充了bindingsource和bindingnavigator。双击GridView中的某个客户,我将看到一个新表单,在该表单中,我将该客户的详细信息显示为详细信息,并可以选择添加新客户。bindingsource只有一个项和上下文。Local也一样。单击导航器中的加号将添加另一个客户,bindingsource现在有两个项目要跟踪while上下文。Local仍然只有一个。我需要让我的上下文知道这个新记录,但我尝试过的一切似乎都

我有一个WinForms应用程序,使用EF6.1。我在表单上自动填充了bindingsource和bindingnavigator。双击GridView中的某个客户,我将看到一个新表单,在该表单中,我将该客户的详细信息显示为详细信息,并可以选择添加新客户。bindingsource只有一个项和上下文。Local也一样。单击导航器中的加号将添加另一个客户,bindingsource现在有两个项目要跟踪while上下文。Local仍然只有一个。我需要让我的上下文知道这个新记录,但我尝试过的一切似乎都在向bindingsource添加另一个记录。这将在尝试保存时给我一个异常,因为不可为null的列未填充。代码如下:

   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();
    }
}
我认为您的问题在于加载数据源的上下文和使保存更改指向内存中不同上下文的上下文。根据Julia Lerman的编程实体框架书

您需要意识到这样一个事实,即 跟踪更改可以保存它们。您不能实例化一个新的上下文并期望它保存对表单中正在使用的实体的更改。它对他们一无所知

因此,务必确保在调用SaveChanges时,使用的上下文与检索数据时使用的上下文相同

解决方案

而不是使用context=newcarsenties。。。在form_load方法中,只需像context=new carsenties…;那样插入上下文即可

然后,在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();
}