Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Object does not match target type in the Save() function when I try to call SetValue(). I stink at reflection.

like image 966
DJ Burb Avatar asked Oct 22 '22 15:10

DJ Burb


1 Answers

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

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

The property belongs to data.ClientBaseObject, so it should be the invocation target. There is no idexer for that property, so if you are on .NET 4.5 or later, you can skip the third parameter altogether.

like image 140
Sergey Kalinichenko Avatar answered Oct 24 '22 09:10

Sergey Kalinichenko