public T Get<T>(int id) where T : BaseModel { string ConnectionString = "Data Source=DESKTOP-63QE7M1; Database=CustomerDB; User ID=sa; Password=sa123; MultipleActiveResultSets=True"; Type type = typeof(T); var propList = type.GetProperties().Select(p => $"[{p.Name}]"); string props = string.Join(',', propList); string tableName = type.Name; string StringSql = $"select {props} from [{tableName}] where id=" + id; object oInstance = Activator.CreateInstance(type); using (SqlConnection connection = new SqlConnection(ConnectionString)) { connection.Open(); SqlCommand sqlCommand = new SqlCommand(StringSql, connection); SqlDataReader reader = sqlCommand.ExecuteReader(); reader.Read(); foreach (var prop in type.GetProperties()) { prop.SetValue(oInstance, reader[prop.Name]); } } return (T)oInstance; }
标签:string,C#,查询方法,prop,reader,泛型,type,id,Name From: https://www.cnblogs.com/xhu218/p/17911142.html