PublicT get<t> (intID) {Type type=typeof(T); stringColumnstrings =string. Join (",", type. GetProperties (). Select (p=>string. Format ("[{0}]"))); stringsql =string. Format ("Select {0} from [{1}] where id={2}", Columnstrings,type. NAME,ID); return default(T); }
Complete example
PublicT get<t> (intID) {Type type=typeof(T); stringColumnstrings =string. Join (",", type. GetProperties (). Select (p=>string. Format ("[{0}]"))); stringsql =string. Format ("Select {0} from [{1}] where id={2}", Columnstrings,type. NAME,ID); Objectt =activator.createinstance (type); using(SqlConnection conn =NewSqlConnection ("Link String") {SqlCommand com=NewSqlCommand (Sql,conn); Conn. Open (); SqlDataReader Reader=com. ExecuteReader (); if(reader. Read ()) {foreach(varIteminchtype. GetProperties ()) {item. SetValue (T,reader[item. Name]); } } } return(t) t; }
Dynamically Stitching SQL statements