Thursday, 18 January 2007


I'm very tired of adding parameters to sqlcommand (or oracledommand, or -best- dbcommand) objects.

I have written a smart code with RTTI, that fills the parameters of dbcommand objects using an "object instance". First it searches for the member fields of the object, then populates the dbcommand object with these name-value pairs.

I didn't tested this code, but I know this approach works well.

public class DbCommandBuilder
/// summary
/// Populates a DbCommand object with the public fields of
/// the given object as parameters.
/// summary
/// param name="command" DbCommand reference to fill
/// param name="obj" Object to get fields of
public void BuildCommand(DbCommand command, object obj)
Type type = obj.GetType();
FieldInfo[] finfos = type.GetFields(BindingFlags.Public);
string fieldName;
object fieldValue;
foreach (FieldInfo fin in finfos)
fieldName = fin.Name;
fieldValue = fin.GetValue(obj);
command.Parameters[fieldName].Value = fieldValue;

No comments: