Nice,
How about adding a couple of other methods
public static void Parameter(IDbCommand command, string naam, object value)
{
IDbDataParameter par = command.CreateParameter();
par.ParameterName = naam;
par.Value = value ?? DBNull.Value;
command.Parameters.Add(par);
}
public static void Fill(IDbCommand command, DataSet dataset, string tableName)
{
if (!dataset.Tables.Contains(tableName))
dataset.Tables.Add(new DataTable(tableName));
Fill(command, dataset.Tables[tableName]);
}
public static void Fill(IDbCommand command, DataTable table)
{
try
{
if (command.Connection.State != ConnectionState.Open)
command.Connection.Open();
table.Load(command.ExecuteReader(CommandBehavior.SingleResult), LoadOption.OverwriteChanges);
}
finally
{
command.Connection.Close();
}
}
public static object FieldByName(IDbCommand command, string naam)
{
try
{
if (command.Connection.State != ConnectionState.Open)
command.Connection.Open();
IDataReader reader = command.ExecuteReader();
if (reader.Read())
return reader[naam];
}
finally
{
command.Connection.Close();
}
return null;
}
public static object FieldByName(DataTable table, string naam)
{
if ((table.Rows.Count <= 0) || (!table.Columns.Contains(naam)))
return null;
return table.Rows[0][naam];
}
public static IList ReadAsList(System.Data.IDbCommand command, Type targetType)
{
Type tList = typeof(List<>).MakeGenericType(targetType);
IList list = (IList)Activator.CreateInstance(tList);
try
{
if (command.Connection.State != System.Data.ConnectionState.Open)
command.Connection.Open();
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
object item = Activator.CreateInstance(targetType);
for (int i = 0; i < reader.FieldCount; i++)
{
foreach (PropertyInfo property in targetType.GetProperties(Flags))
{
if ((property.Name == reader.GetName(i)) && (property.CanWrite))
property.SetValue(item, reader.GetValue(i), null);
}
}
list.Add(item);
}
}
finally
{
command.Dispose();
}
return list;
}
public static object ReadAsObject(System.Data.IDbCommand command, Type targetType)
{ try
{
if (command.Connection.State != System.Data.ConnectionState.Open)
command.Connection.Open();
IDataReader reader = command.ExecuteReader();
if (reader.Read())
{
object item = Activator.CreateInstance(targetType);
for (int i = 0; i < reader.FieldCount; i++)
{
foreach (PropertyInfo property in targetType.GetProperties(Flags))
{
if ((property.Name == reader.GetName(i)) && (property.CanWrite))
property.SetValue(item, reader.GetValue(i), null);
}
}
return item;
}
}
finally
{
command.Dispose();
}
return null;
}
Or even how about using
DataContext
.
That would be easy enough.
using(var database = new DataContext(connectionString)){
int result = database.ExecuteCommand(query, parameters);
ResultObject result = database.ExecuteQuery<resultobject>(query, parameters).FirstOrDefault();
}</resultobject>