views:

36

answers:

1

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

A: 

Try using the methods listed here: http://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-class

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

Preet Sangha
And for real speed, you can use the information to generate code that quickly and natively accesses these properties.
Steven Sudit
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