我正在使用 VS 2019,帶有 Win 表單和物體框架核心 5.0 的 c# 應用程式
在我的應用程式中,我有一個 System.Windows.Forms.DataGridView 用于顯示和更新 MySQL 資料庫中的資料。資料通過使用 System.Windows.Forms.BindingSource myBindingSource 系結到 DataGridView 并使用系結 EF 表資料
myDbContext.SomeEntities.Load();
myBindingSource.DataSource = myDbContext.SomeEntities.Local.ToBindingList();
這確實正確顯示了資料,一旦我更改了網格中的一些資料并呼叫 myDbContext.SaveChanges() 它就會將資料保存到資料庫中。
因此,只要應用程式獨立運行,它就可以正常作業。
但是,我想要實作的是,每當我的應用程式之外的任何其他操作更改資料時,包含網格的表單都會重繪 資料。因此,如果對資料的任何更新發生在我的應用程式之外,我希望這些更改在打開的表單中立即可見,而無需用戶關閉并重新打開包含 DataGridView 的表單。我當然知道,我需要觸發這些變化。那可能是計時器或外部信號。現在它是一個計時器。
在計時器中,我做了一個
foreach( var rec in (BindingList<SomeEntities>)this.DataSource)
{
DbContext.Entry(rec).Reload();
}
然后我做了一個
CurrencyManager cm = (CurrencyManager)((myDataGridView).BindingContext)[(ctrl as DataGridView).DataSource];
if (cm != null) cm.Refresh();
這適用于現有記錄的外部更新。但是,如果插入或洗掉記錄,則會失敗。外部插入時,新記錄在現有的 BindingList 中根本不知道,因此不會重繪 ;當從外部洗掉記錄時,重新加載失敗(因為它不再存在于資料庫中)。對于正在發生的事情,兩者都是可以理解的。
不僅重繪 現有物體而且重繪 集合 myDbContext.SomeEntities 的內容的正確方法是什么
在尋找答案時,我經常讀到“使用 DbContext 的短生命周期”。可以理解,但我確實需要 DbContext 才能呼叫 myDbContext.SaveChanges() 以保存在網格中所做的任何更改。我嗎?或者還有其他方法嗎?如果 DbContext 僅在加載網格期間使用,我如何使用常規資料系結將其用作網格的資料源?
使用 EntityFramework 6 有
_myObjectContext.RefreshAsync(RefreshMode.StoreWins, GetAll())
不知道這是否會有所幫助,因為我沒有嘗試使用 EntityFramework 6,但無論如何,在 EF 核心中沒有與此等效的方法。那么有什么建議嗎?
uj5u.com熱心網友回復:
我認為在這種情況下 - 當您一直打開資料網格時(據我所知),這應該更多地手動完成。
例如,使用 MVVM,我將創建一個帶有一些可觀察的視圖項集合的 ViewModel,例如:
假設這是您的資料庫模型:
public class DbItem
{
public int Id {get;set;}
public string Name {get;set;}
}
現在,我將創建一些要在視圖模型中使用的資料:
public class ItemData: INotifyPropertyChanged
{
public ItemData(DbItem item)
{
id = item.Id;
name = item.Name; //notice that I use here backup field
}
public bool Modified {get; private set;}
int id;
public int Id
{
get { return id; }
set
{
if(id != value)
{
id = value;
NotifyPropertyChanged();
}
}
}
string name;
public string Name
{
get { return name; }
set
{
if(name != value)
{
name = value;
NotifyPropertyChanged();
}
}
}
}
在這里,我使用了 INotifyPropertyChanged,但這一切都歸結為您的需求。您可以將欄位更新Modified為 true,或者每次記錄更改時,只需在資料庫中更新它(SQL UPDATE/INSERT)
現在在我的 ViewModel 中,我會這樣做:
public class ViewModel
{
public ObservableCollection<ItemData> DataSource {get; set;}
}
我懷疑您是否可以像在 WPF 中一樣在 WinForms 中使用 ObservableCollection,因此我認為您可以創建一些系結集合。
無論如何,現在當您從資料庫中讀取資料時,您應該將它們轉換為您的專案:
public class ViewModel
{
public void ReadData()
{
DataSource.Clear();
List<DbItem> dbItems = service.GetDataFromDatabaseWithNoTracking();
foreach(var item in dbItems)
{
DataSource.Add(new ItemData(item));
}
}
}
現在,當您需要更新某些內容時,只需:
public class ViewModel
{
public void UpdateData(ItemData data)
{
//if data.Modified...
DbItem db = new DbItem();
db.Id = data.Id;
db.Name = data.Name;
service.UpdateItem(db);
}
}
在 EF 中:
public void UpdateItem(DbItem item)
{
var entry = dbContext.Entry(item);
dbContext.Save();
}
歸根結底,您不會跟蹤資料庫中的記錄。您應該手動執行此操作。
您如何看待這個解決方案?
uj5u.com熱心網友回復:
我不確定這是否是一個不錯的界面。假設操作員正在愉快地編輯一行,突然您決定重新加載表:他的所有更改都丟失了嗎?如果運算子只是將一個值從 4 更改為 5,而其他人只是將相同的值從 4 更改為 3,我們應該保留哪個?如果其他人決定洗掉一行怎么辦,因為他認為
所以我建議不要進行自動重繪 ,為此添加一個按鈕。類似于瀏覽器中的重新加載按鈕。添加 F5 按鈕開始重繪 ,您的界面與大多數可能顯示過時資料的 Windows 應用程式兼容。
但是,這有一個缺點,如果操作員編輯了一個值,其他人也編輯了,甚至洗掉了,您應該決定要做什么。我的建議是:詢問接線員:
- 如果操作員編輯了其他人也編輯過的一行:我們應該保留哪一行?
- 如果操作員編輯了其他人洗掉的行?
- 如果操作員洗掉了其他人剛剛更改的行?
讓我們假設您的 datagridview 顯示Products:
class Product
{
public int Id {get; set;}
public string Name {get; set;}
public decimal Price {get; set;}
public int Stock {get; set;}
...
}
使用 Visual Studio 設計器,您添加了一個 DataGridView 和一些列。在您的建構式中,您可以為列分配屬性:
public MyForm() : Form
{
InitializeComponents()
this.columnId.DataPropertyName = nameof(Product.Id);
this.columnName.DataPropertyName = nameof(Product.Name);
this.columnPrice.DataPropertyName = nameof(Product.Price);
...
}
您還需要一種方法來獲取必須從資料庫中顯示的產品,然后再次重新獲取它們,以查看更改了哪些產品。當然,您隱藏它們來自資料庫。
IEnumerable<Product> FetchProductsToDisplay()
{
... // Fetch the data from the database; out-of-scope of this question
}
要顯示獲取的產品,請使用 DataSource 和 BindingList:
BindingList<Product> DisplayedProducts
{
get => (BindingList<Product>)this.dataGridView1.DataSource;
set => this.dataGridView1.DataSource = value;
}
最初您展示產品:
void OnFormLoading(object sender, ...)
{
this.DisplayedProducts = this.FetchProductsToDisplay()
}
So now the operator happily can edit existing Products, maybe add some new ones, or remove some Products. After a while he wants to refresh the Products with the data others entered:
private void OnButtonRefresh_Clicked(object sender, ...)
{
this.UpdateProducts();
}
private void UpdateProducts()
{
IEnumerable<Product> dbProducts = this.FetchProductsToDisplay();
IEnumerable<Product> editedProducts = this.DisplayedProducts();
We have to compare the Products from the database with the Products in the DataGridView. Match the Products by Id: same Id, expect same Product.
- Id is zero, and thus only in editedProducts, it has been added by the operator, but not added to the database yet.
- non-zero Id is only in editedProducts: it has been deleted by someone else
- Id is both in dbProducts and in editeProducts, but values not equal: either edited by the operator, or by someone else
A difficult one:
- Id is only in dbProducts: it has been added by someone else, or deleted by operator.
To be able to ask the operator the correct question, it seems that we also need the Products that were displayed before the operator started to edit.
private IEnumerable<Product> OriginalProducts => ...
So now we are able to detect which products are added / removed / changed, by the operator and/or in the database:
Id in originalProducts editedProducts dbProducts
yes yes yes compare values to detect edits
yes yes no someone else deleted
yes no yes operator deleted.
yes no no both operator and someone else deleted
no no yes someone else added
no yes no operator added
no yes yes both operator and someone else added
The procedure to detect changes:
private void DetectChanges(IEnumerable<Product> originalProducts,
IEnumerable<Product> editedProducts,
IEnumerable<Product> dbProducts)
{
// do a full outer join on these three sequences:
var originalDictionary = originalProducts.ToDictionary(product => product.Id);
var dbDictionary = dbProducts.ToDictionary(product => product.Id);
// some Ids in editedProducts have value zero:
var addedProducts = editedProducts.Where(product => product.Id == 0);
var editedDictionary = editedProducts.Where(product => product.Id != 0)
.ToDictionary(product => product.Id);
var allUsedIds = originalDictionary.Keys
.Concat(dbDictionary.Keys)
.Distinct();
Note: all editedProducts with Id != 0 already existed in the database when they were last fetched, so their Ids are already in originalDictionary. I used Distinct to remove duplicate Ids
foreach (int id in allUsedIds)
{
bool idInDb = dbDictionary.TryGetValue(id, out Product dbValue)
bool idInOriginal = originalDictionary.TryGetValue(id, out Product originalValue);
bool idInEdited = editedDictionary.TryGetValue(id, out Product editedValue);
Use the table from above, and the values idInDb / idInOriginal / idInEdited to find out if the value has been added or removed / changed.
Sometimes it will be enough to just Add / Edit / Change the value in the DataGridView; sometimes you'll have to ask the operator.
Advice:
Changes made by someone else:
- If added by someone else: just add it to the DataGridView
- If removed by someone else, not edited by operator: just remove from DataGridView
- If removed by someone else, edited by operator: ask operator what to do
Changes made by the operator:
If added by operator (Id == 0): insert in the database
If removed by operator, remove it from database
If edited by operator, not by someone else: update the database
Changes made by the operator and by someone else: ask operator which one to keep. Either update the database or the DataGridView.
Detect Product Changes: use IEqualityComparer
To detect change, you need an equality comparer that compares by value:
public class ProductComparer : EqualityComparer<Product>
{
public static IEqualityComparer<Product> ByValue {get} = new ProductComparer();
public override bool Equals(Product x, Product y)
{
if (x == null) return y == null; // true if both null
if (y == null) return false; // because x not null
if (Object.ReferenceEquals(x, y) return true; // same object
if (x.GetType() != y.GetType()) return false; // different types
return x.Id == y.Id
&& x.Name == y.Name // or use StringComparer.CurrentCultureIgnoreCase
&& x.Price == y.Price
&& ...
}
public override int GetHashCode(Product x)
{
if (x == null) return 87742398;
// for fast hash code: use Id only.
// almost all products are not edited, so with same Id have same values
return x.Id.GetHashCode();
}
}
Usage: IEqualityComparer productValueComparer = ProductComparer.ByValue;
After detecting which products are in which dictionary:
if (idInDb && idInEdited && )
{
// one of the Products in the DataGridView already exists in the database
// did the operator edit it?
bool operatorChange = !productValueComparer.Equal(originalValue, editedValue);
bool dbChange = !productValueComparer.Equal(originalValue, dbValue);
if (!productValueComparer.Equal(operatorValue, dbValue);)
{
// operator edited the Product; someone change it in the database
// ask operator which value to keep
...
}
else
{
// operator edited the Product; the same value is already in the database
// nothing to do.
}
So for every Id, check if it was already in the database, check if it is still in the database and check if the operator kept it in the dataGridView. Also check which values are changed, to detect whether you need to add / remove / update the database, or the DataGridView or maybe you have to do nothing.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/332908.html
