Updating Multiple Fields via LINQ and Reflection Automatically (EF4)

You can use reflection to avoid manually entering a ton of fields

Recently, the question was asked on Stackoverflow about updating multiple integer fields in an EF4 object without having to type each out manually. I had run into a similar problem like this in the recent past where I had a large number of int fields (38 to be exact) and I didn't really want to write in 38 lines of essentially the same thing into my code. Instead, I cam up with this using Reflection. This simple example shows an object 'o' and a single new value 'newValue', but you can easily use an array or list as well for inserting values - this just gets the point across:
foreach(PropertyInfo prop in o.GetType().GetProperties()) 
{
    if(prop.PropertyType == typeof(int))
        prop.SetValue(o, newValue, null);
}

You can see in this example, I look only for integer fields, but it would be simple to check for any other type of field, or name, or a field that has a name that starts with 'abcd' - the list is endless and simple to adapt to.

Comments (1) -

  • Good article - it's a great example of how following the book isn't always the best idea and a bit of lateral thinking not only reduces code but makes the code clearer and cleaner.

    One last thing, you've got a typo in the header "refelection"

    Keep up the good work Smile
Comments are closed