views:

49

answers:

1

I have a model called "Channel" which has a bunch of string properties.

I fetch data from my data source which returns a hash table. The Keys of this table match the property names of my model.

How can I auto-bind the hash table to the Channel model?

The binders from ASP.NET MVC seem to do this but you need to use it in a controller with context. I don't want to pass context into my repository to make it work when fetching data. (although I guess I can if needed)

+1  A: 

The method itself is so trivial that you just can't expect "existing" solution for it:

public static T Bind<T>(IDictionary<string, string> hash, T channel)
{
   foreach (var item in hash)
   {
        var prop = typeof(T).GetProperty(item.Key);
        prop.SetValue(channel, Convert.ChangeType(item.Value, prop.PropertyType), new object[0]);
   }
}

That's everything you need. Now you can use this method standalone without any controller, or write a model binder that uses it.

There can be more work with nested properties (you didn't say you need that) but it's 5 more minutes to write using recursion.

queen3