C# 利用泛型、反射实现数据库的增删查改
-
数据查询
public T QueryDomain<T>(int id) { Type type = typeof(T); T t = (T)Activator.CreateInstance(type); string columns = string.Join(",", type.GetProperties().Select(p => string.Format("[{0}]", p.Name))); string sql = string.Format("select {0} from [{1}] where id={2}", columns, type.Name, id); string ConnectionString = ConfigurationManager.AppSettings["SqlServerConnString"]; using (SqlConnection sqlConnection = new SqlConnection(ConnectionString)) { SqlCommand command = new SqlCommand(sql, sqlConnection); sqlConnection.Open(); SqlDataReader dataRead = command.ExecuteReader(CommandBehavior.CloseConnection); if (dataRead.Read()) { foreach (var prop in type.GetProperties()) { prop.SetValue(t, Convert.ChangeType(dataRead[prop.Name], pr