【问题标题】:How can I output a list of field names and values that were changed?如何输出已更改的字段名称和值的列表?
【发布时间】:2013-11-05 21:29:49
【问题描述】:

在构建 MVC Web 应用程序时,我仍在学习 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
            }
        }

因为我仍在学习,所以我希望获得有关阅读什么主题或我可以在哪里独立研究答案的指导/提示。目前,我的技能差距使我无法研究解决方法。

提前致谢。

【问题讨论】:

    标签: c#


    【解决方案1】:

    您可以尝试将反射用于您的目的。像这样的

    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
        }
     }
    

    【讨论】:

      【解决方案2】:

      我想我找到了我正在寻找的提示......

      System.Reflection

      更具体地说,FieldInfo.GetValue() 方法。

      我以前不知道 System.Reflection 是什么,所以我将进一步研究这个领域以找到我的解决方案。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 2021-11-01
      • 1970-01-01
      • 2022-11-20
      相关资源
      最近更新 更多