【问题标题】:Entity Framework and bindingNavigator.AddNew using details in WinForms实体框架和 bindingNavigator.AddNew 使用 WinForms 中的详细信息
【发布时间】:2014-06-12 08:33:17
【问题描述】:

我有一个使用 EF6.1 的 WinForms 应用程序。我在表单上自动填充了 bindingsource 和 bindingnavigator。在 GridView 中双击一个客户会引导我进入一个新表单,在该表单中我会将此客户的详细信息显示为详细信息,并可选择添加新客户。 bindingsource 只有一项,context.Local 也一样。单击导航器中的加号会添加另一个客户,并且 bindingsource 现在有两个项目要跟踪,而 context.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();
    }
}

【问题讨论】:

    标签: c# entity-framework data-binding


    【解决方案1】:

    我认为您的问题是 context 加载 DataSource 和 context 以使 SaveChanges 指向内存中的不同 contexts。根据 Julia Lerman 的Programming Entity Framework一书,

    您需要注意这样一个事实,即只有上下文 跟踪更改能够保存它们。您不能实例化一个新的上下文并期望它保存对您在表单中使用的实体的更改。它不会知道关于他们的任何事情。

    因此,重要的是要确保当您调用 SaveChanges 时,您使用的是用于检索数据的同一上下文。

    解决方案

    在 form_load 方法中不要使用 using (context = new CarsEntities(...)),而是像 context = new CarsEntities(...); 那样启动上下文。

    然后,在form_closure方法中,输入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();
    }
    

    希望此解决方案对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多