Object does not match target type when trying to use SetValue

public class ConflictSaver
{
    private readonly IEnumerable<CommonJobDataInfo> _conflictingJobData;
    private readonly DataAccessDataContext _dc;

    public ConflictSaver(IEnumerable<CommonJobDataInfo> conflictingJobData, DataAccessDataContext dc)
    {
        _conflictingJobData = conflictingJobData;
        _dc = dc;
    }

    public void Save()
    {
        foreach (var data in _conflictingJobData)
        {
            var type = data.ClientBaseObject.GetType();
            var formattedProperty = data.Property.Trim('.').ToUpper();
            foreach (var property in type.GetProperties())
            {
                var currentProperty = data.ClientBaseObject.GetType().GetProperties().First(t => t.Name.Trim() == property.Name.Trim());

                if(currentProperty.Name.ToUpper()== formattedProperty)
                {
                    if (data.UseServerValue)
                        currentProperty.SetValue(currentProperty, data.ServerValue, null);
                    else
                        currentProperty.SetValue(currentProperty, data.ClientValue, null);
                }
            }

        }
    }
}  

I get the Object does not match the type of the target in the Save () function when I try to call SetValue (). I stink on reflection.

+5
source share
1 answer

It looks like you are using the wrong overload and passing the wrong object:

if (data.UseServerValue)
    currentProperty.SetValue(data.ClientBaseObject, data.ServerValue);
else
    currentProperty.SetValue(data.ClientBaseObject, data.ClientValue);

The property belongs data.ClientBaseObject, so it should be the target of the call. There is no idexer for this property, so if you are using .NET 4.5 or later , you can skip the third parameter altogether.

+3
source

All Articles