[英]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.