Simplest way to populate class from query in C# -
i want populate class query. example class:
private class tvchannelobject { public string number { get; set; } public string title { get; set; } public string favoritechannel { get; set; } public string description { get; set; } public string packageid { get; set; } public string format { get; set; } }
how can fill class database query? there way automatically far table column names identical class attributes?
as others have suggested, orm best way go. could, however, implement functionality using reflection:
void main() { var connectionstring = "..."; var records = new query(connectionstring).sqlquery<tvchannel>("select top 10 * tvchannel"); } private class tvchannel { public string number { get; set; } public string title { get; set; } public string favoritechannel { get; set; } public string description { get; set; } public string packageid { get; set; } public string format { get; set; } } public class query { private readonly string _connectionstring; public query(string connectionstring) { _connectionstring = connectionstring; } public list<t> sqlquery<t>(string query) { var result = new list<t>(); using (var connection = new sqlconnection(_connectionstring)) { connection.open(); using (var command = connection.createcommand()) { command.commandtext = query; using (var reader = command.executereader()) { var columns = enumerable.range(0, reader.fieldcount).select(reader.getname).toarray(); var properties = typeof(t).getproperties(); while (reader.read()) { var data = new object[reader.fieldcount]; reader.getvalues(data); var instance = (t)activator.createinstance(typeof(t)); (var = 0; < data.length; ++i) { if (data[i] == dbnull.value) { data[i] = null; } var property = properties.singleordefault(x => x.name.equals(columns[i], stringcomparison.invariantcultureignorecase)); if (property != null) { property.setvalue(instance, convert.changetype(data[i], property.propertytype)); } } result.add(instance); } } } } return result; } }
Comments
Post a Comment