简体   繁体   中英

How can I output a list of field names and values that were changed?

I'm still learning C# whilst building an MVC web app. Trying to find a way to create a list of values that were changed by a user during an edit operation.

Here's one way I have that would work:

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;

    }

But... As you can tell, I am going to need to write an IF/ELSE statement for every single field in my database. There are about 200 fields in there. I'm also worried that it's going to take a long time to work through the list.

Is there some way to go through the list of properties for my object iteratively, comparing them to the database record, changing them if necessary and then outputting a list of what changed.

In pseudo code this is what I guess I am after:

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

Because I'm still learning I would appreciate guidance/tips on what subject matter to read about or where I can independently research the answer. The gaps in my skill are currently stopping me from being able to even research a solution approach.

Thanks in advance.

You can try to use Reflection for your purposes. Something like this

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

I think I have found the hint I was looking for...

System.Reflection

More specifically, the FieldInfo.GetValue() method.

I was previously unaware of what System.Reflection was all about, so I'll research this area further to find my solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM