3

I've a similar error to this one, but unfortunately not the same simple solution. Here is the code:

public virtual void MapObject(T obj, IViewModel<T> viewModel, ITPSDataAccess dataAccess)
{
    var objProps = obj.GetType().GetProperties();
    var dtoProps = viewModel.GetType().GetProperties();
    foreach (var dtoProp in dtoProps)
    {
        var objProp = dtoProps.SingleOrDefault(x => x.Name == dtoProp.Name);
        if (objProp != null)
        {
            var dtoVal = dtoProp.GetValue(viewModel, null);
            objProp.SetValue(obj, dtoVal, null); // ERROR HERE
        }
    }
     ...
}

The error occurs at the point indicated, stating "Object does not match target type". It looks like I'm passing the correct object to be set - I am therefore unable to solve the problem.

I've also tried to take the advice of this solution, and examine the types of property I'm attempting to set which throw the exception - the property in question is a string, and the setter does not appear to be broken since it works under normal, non-reflection circumstances.

Community
  • 1
  • 1
Hanshan
  • 3,656
  • 5
  • 29
  • 36
  • Add `objProp.PropertyType` and `dtoVal.GetType()` to the Watch debugger window, and set a breakpoint on the call to `objProp.SetValue(...)`. When the breakpoint is hit, what do those two expressions evaluate to? They need to be the same. – Michael Liu Jan 30 '12 at 04:05

1 Answers1

3

The mistake seems to be here:

var objProp = dtoProps.SingleOrDefault(x => x.Name == dtoProp.Name);

I think you meant:

var objProp = objProps.SingleOrDefault(x => x.Name == dtoProp.Name); 
Igby Largeman
  • 16,495
  • 3
  • 60
  • 86
  • THanks, man - that was one of those ones you stare at for 30mins and it takes 3s for someone else to see it... ! – Hanshan Jan 30 '12 at 04:14