Skip to content

Instantly share code, notes, and snippets.

@Nyconing
Created February 27, 2020 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nyconing/924616104fa411e7dabb233d16f37829 to your computer and use it in GitHub Desktop.
Save Nyconing/924616104fa411e7dabb233d16f37829 to your computer and use it in GitHub Desktop.
QuerySchemaClass
public TA[] QuerySchemaClass<TA>(string query, Func<TA> classCreator, SqlParameter[] parameters) where TA : class {
if (!IsConnected) throw new Exception("Database is not connected.");
var cmd = new SqlCommand(query, Connection);
if (parameters != null && parameters.Length > 0) {
foreach (var parameter in parameters) {
cmd.Parameters.Add(parameter);
}
}
var cs = cmd.ExecuteReader();
var dt = new List<TA>();
var classProps = typeof(TA).GetProperties().ToDictionary(x => x.Name);
if (cs.HasRows) {
while (cs.Read()) {
var row = classCreator();
var c = -1;
do {
c++;
var value = cs.GetValue(c);
classProps[cs.GetName(c)].SetValue(row, value == DBNull.Value ? null : value);
} while (c + 1 != cs.FieldCount);
dt.Add(row);
}
}
cs.Close();
return dt.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment