loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Updating Multiple Fields via LINQ and Reflection Automatically (EF4)

by naspinski 5/23/2011 4:00:00 PM

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.

Currently rated 2.7 by 15 people

  • Currently 2.733334/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

c# | entities | linq | linq-to-sql | steal some code

Related posts

Comments

6/22/2011 7:16:22 PM

Norris Ewelike
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

Norris Ewelike gb


Comments are closed