【问题标题】:EF6 Context lost when using subset使用子集时 EF6 上下文丢失
【发布时间】:2018-02-13 13:16:15
【问题描述】:

您好,我有一个表“供应商”和另一个“SupplierPlants”,我将两个表都通过代码绑定到 DataGridViews:

        bsSuppliers = new BindingSource();
        bsSuppliers.DataSource = AppData.Suppliers;
        bsSuppliers.AllowNew = true;
        dgvSuppliers.DataSource = bsSuppliers;
        dgvSuppliers.Refresh();

        bsSuppliersPlants = new BindingSource();
        bsSuppliersPlants.DataSource = AppData.SupplierPlants;
        bsSuppliersPlants.AllowNew = true;
        dgvSupplierPlants.DataSource = bsSuppliersPlants;
        dgvSupplierPlants.Refresh();

AppData 类包含我所有的数据库实体:

        Db = new PureTrialEntities();

        Db.Suppliers.Load();
        Suppliers = Db.Suppliers.Local;

        Db.SupplierPlants.Load();
        SupplierPlants = Db.SupplierPlants.Local;

现在我为供应商 DataGridView 绑定了 RowEnter 事件,以便它只显示所选供应商的植物:

    private void dgvSuppliers_RowEnter(object sender, DataGridViewCellEventArgs e)
    {
        var supplier = ((Supplier)dgvSuppliers.Rows[e.RowIndex].DataBoundItem);
        if (supplier == null)
            return;

        ShowSupplierPlants(supplier.SupplierID);
     }

    private void ShowSupplierPlants(int supplierID)
    {
        var plantData = AppData.SupplierPlants.Where(x => x.SupplierID == supplierID); //Get selected Suppliers Plant Data.
        if (plantData.Any())
            bsSuppliersPlants.DataSource = plantData;
        else
            bsSuppliersPlants.DataSource = new List<SupplierPlant>();

        dgvSupplierPlants.Refresh();
    }

问题是当我调用 AppData.Db.SaveChanges(); 时,它会正确地将所有更改应用到 Suppliers 表,但它不会为 SupplierPlants 表添加新行,因为我已经获取了一个子集本地数据库的。 当我使用的是子集而不是整个本地数据库时,是否必须手动管理为此表添加的新行?

【问题讨论】:

    标签: c# .net entity-framework data-binding datagridview


    【解决方案1】:

    您应该手动插入它们,

    Db.SupplierPlants.Add(item);
    

    详细information

    希望有帮助,

    【讨论】:

    • 是的,该链接很有帮助,谢谢,当单元格编辑结束时,我可以通过将其添加到本地轻松地将其添加到上下文中。
    【解决方案2】:

    仅供参考,我绑定了 DGV CellEndEdit 并将新添加的行添加到上下文中,如下所示:

     private void dgvSupplierPlants_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var data = ((SupplierPlant)((DataGridView)sender).Rows[e.RowIndex].DataBoundItem); //Get the Data for the edited Row.
            if (AppData.Db.Entry(data).State == EntityState.Detached)
            {
                AppData.SupplierPlants.Add(data);
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2010-10-22
      相关资源
      最近更新 更多