0

I have several methods that populate a SQLCommand objects parameter collection from an object like this

if (!String.IsNullOrEmpty(SearchObj.FirstName))
{
    command.AddParameter(Fields.FirstName, SearchObj.FirstName);
}
if (!String.IsNullOrEmpty(SearchObj.LastName))
{
    command.AddParameter(Fields.LastName, SearchObj.LastName);
}
if (!String.IsNullOrEmpty(SearchObj.EmailAddress))
{
    command.AddParameter(Fields.EmailAddress, SearchObj.EmailAddress);
}
if (SearchObj.JobRoleId > -1)
{
    command.AddParameter(Fields.JobRoleId, SearchObj.JobRoleId);
}

This can get messy as the object can have up to about 20 properties. Is there anyway using reflection to loop through each of these properties and add them all to the Sqlcommand objects Parameter collection? Bearing in mind it treats strings different to ints in that it only adds a string if its not null or empty and it only adds an int if its greater than -1.

I've not used much reflection before, so a point in the right direction would be great.

Thanks

Gavin
  • 17,053
  • 19
  • 64
  • 110

1 Answers1

0

Try using the methods listed here: How to get the list of properties of a class?

and then loop over them adding them as you see fit.

Community
  • 1
  • 1
Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
  • And for real speed, you can use the information to generate code that quickly and natively accesses these properties. – Steven Sudit Sep 04 '09 at 11:45
  • Yes, and honestly this is where the DLR is a superb choice for this. We've taken and a lot of reflection for unknown objects and replaced them with DLR calls. The performance is excellent. – Preet Sangha Sep 05 '09 at 00:24