[英]How can I output a list of field names and values that were changed?
在構建MVC網絡應用時,我仍在學習C#。 試圖找到一種方法來創建由用戶在編輯操作期間更改的值的列表。
這是我可以使用的一種方法:
public List<string> SaveVehicleTechnicalInformation(VehicleAssetTechnicalInformationViewModel editmodel)
{
// Create a list of fields that have changed
List<string> changes = new List<string>();
var record = db.VehicleAssetTechnicalInformations.Find((int)editmodel.RecordID);
if (editmodel.Make != null && editmodel.Make != record.Make)
{
changes.Add(" [Make changed from " + record.Make + " to " + editmodel.Make + "] ");
record.Make = editmodel.Make;
}
if (editmodel.Model != null && editmodel.Model != record.Model)
{
changes.Add(" [Model changed from " + record.Model + " to " + editmodel.Model + "] ");
record.Model = editmodel.Model;
}
return changes;
}
但是...正如您所知道的,我將需要為數據庫中的每個字段編寫一個IF / ELSE語句。 那里大約有200個字段。 我還擔心要花很長時間才能完成列表。
有什么方法可以迭代遍歷我對象的屬性列表,將它們與數據庫記錄進行比較,如果需要的話可以更改它們,然后輸出更改內容的列表。
用偽代碼,這就是我想得到的:
foreach (var field in editmodel)
{
if (field != database.field)
{
// Update the value
// Write a string about what changed
// Add the string to the list of what changed
}
}
因為我仍在學習,所以我希望能獲得有關要閱讀哪些主題或可以在何處獨立研究答案的指導/提示。 我目前技能上的不足使我無法研究解決方案。
提前致謝。
您可以嘗試將Reflection用於您的目的。 像這樣
var fields = editmodel.GetType().GetFields();
foreach (var item in fields)
{
if (item.GetValue(editmodel) == database.field)
{
// Update the value
// Write a string about what changed
// Add the string to the list of what changed
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.