What is the best way to map from/to a Dictionary with objects properties based on an interface as contract?

786 Views Asked by At

I'm working on a very dynamic Silverlight Application where viewmodels are dynamic models. The WCF service returns a Response object that contains enough information (TableName property and an Dictionary[] array containing entities).

So, suppose I have a single entity (Dictionary) and some instance of viewmodel that is an object of any kind. The key of the dictionary serves as the property name, and obviously, the value will be used to set the property value in the viewmodel. I need to map values from this dictionary to values of the dynamic viewmodel and vice-versa. In order to have some constraints on this mappings, I created interfaces to validate the values of the dictionary, so I only get/set values if the values propertynames are defined in the contract.

I know about duck typing, dynamic proxies, object mappers, and I know how to use reflection.

I started to searching for some tool or framework that can turn this task easy. So I've found Impromptu-Interface. I'm trying to do this with Impromptu-interface:

  public static TContract MapFromDictionary<TContract>(object bindingModel, Dictionary<string, object> data) where TContract : class {
  var proxy = new ImpromptuDictionary(data).ActLike<TContract>();
  var properties = Impromptu.GetMemberNames(proxy);
  foreach (var propertyName in properties) {
    object value = Impromptu.InvokeGet(proxy, propertyName);
    Impromptu.InvokeSet(bindingModel, propertyName, value);
  }
  return bindingModel.ActLike<TContract>();
}

Works like a charm.

And the reverse mapping:

  public static Dictionary<string, object> MapToDictionary<TContract>(object source) where TContract : class {
  var proxy = source.ActLike<TContract>();
  var result = new Dictionary<string, object>();
  var properties = Impromptu.GetMemberNames(proxy);

  foreach (var propertyName in properties) {
    object value = Impromptu.InvokeGet(proxy, propertyName);
    result.Add(propertyName, value);
  }

  return result;
}

The question is: Is there any better way to do this ?

1

There are 1 best solutions below

2
On

You should be able to just use LINQs ToDictionary method instead of the foreach. For a collection, it just takes a lambda that shows it how to get a key.