我编写了一系列扩展方法,以使其更易于操作ADO.NET对象和方法:
在一条指令中从DbConnection创建DbCommand:
public static DbCommand CreateCommand(this DbConnection connection, string commandText)
{
DbCommand command = connection.CreateCommand();
command.CommandText = commandText;
return command;
}
向DbCommand添加参数:
public static DbParameter AddParameter(this DbCommand command, string name, DbType dbType)
{
DbParameter p = AddParameter(command, name, dbType, 0, ParameterDirection.Input);
return p;
}
public static DbParameter AddParameter(this DbCommand command, string name, DbType dbType, object value)
{
DbParameter p = AddParameter(command, name, dbType, 0, ParameterDirection.Input);
p.Value = value;
return p;
}
public static DbParameter AddParameter(this DbCommand command, string name, DbType dbType, int size)
{
return AddParameter(command, name, dbType, size, ParameterDirection.Input);
}
public static DbParameter AddParameter(this DbCommand command, string name, DbType dbType, int size, ParameterDirection direction)
{
DbParameter parameter = command.CreateParameter();
parameter.ParameterName = name;
parameter.DbType = dbType;
parameter.Direction = direction;
parameter.Size = size;
command.Parameters.Add(parameter);
return parameter;
}
通过名称而不是索引访问DbDataReader字段:
public static DateTime GetDateTime(this DbDataReader reader, string name)
{
int i = reader.GetOrdinal(name);
return reader.GetDateTime(i);
}
public static decimal GetDecimal(this DbDataReader reader, string name)
{
int i = reader.GetOrdinal(name);
return reader.GetDecimal(i);
}
public static double GetDouble(this DbDataReader reader, string name)
{
int i = reader.GetOrdinal(name);
return reader.GetDouble(i);
}
public static string GetString(this DbDataReader reader, string name)
{
int i = reader.GetOrdinal(name);
return reader.GetString(i);
}
...
另一种(不相关的)扩展方法使我可以在WinForms表单和控件上执行DragMove操作(如WPF),请参见此处。