[英]EF6 Context lost when using subset
Hi I have a Table 'Suppliers' and another 'SupplierPlants' I have both tables bound to DataGridViews via code: 嗨,我有一个表'Suppliers'和另一个'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();
The AppData class holds all of my DB entities: AppData类包含我所有的数据库实体:
Db = new PureTrialEntities();
Db.Suppliers.Load();
Suppliers = Db.Suppliers.Local;
Db.SupplierPlants.Load();
SupplierPlants = Db.SupplierPlants.Local;
Now I have RowEnter event bound for the Supplier DataGridView so that it will only show Plants for the selected Suppliers: 现在,我为供应商DataGridView绑定了RowEnter事件,因此它将仅显示所选供应商的Plants:
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();
}
The issue is when I call AppData.Db.SaveChanges(); 问题是当我调用AppData.Db.SaveChanges()时; it will correctly apply all changes to the Suppliers Table but it wont Add new rows for the SupplierPlants table as I have taken a subset of the local db.
它将正确地将所有更改应用到Suppliers表,但是由于我已经获取了本地数据库的一个子集,因此不会为SupplierPlants表添加新行。 Do I have to manually manage new rows added for this Table as I am using a subset and not the whole Local db?
当我使用子集而不是整个本地数据库时,是否必须手动管理为此表添加的新行?
You should insert them manually, 您应该手动插入它们,
Db.SupplierPlants.Add(item);
Detailed information 详细资料
Hope helps, 希望有帮助,
just as a FYI i bound the DGV CellEndEdit and just added the newly added line to the context like so: 就像供参考一样,我绑定了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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.