[英]EF6 Context lost when using subset
嗨,我有一個表'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();
AppData類包含我所有的數據庫實體:
Db = new PureTrialEntities();
Db.Suppliers.Load();
Suppliers = Db.Suppliers.Local;
Db.SupplierPlants.Load();
SupplierPlants = Db.SupplierPlants.Local;
現在,我為供應商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();
}
問題是當我調用AppData.Db.SaveChanges()時; 它將正確地將所有更改應用到Suppliers表,但是由於我已經獲取了本地數據庫的一個子集,因此不會為SupplierPlants表添加新行。 當我使用子集而不是整個本地數據庫時,是否必須手動管理為此表添加的新行?
就像供參考一樣,我綁定了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.