C#的相关知识,封装一个泛型的数据库访问查询方法

发布时间 2023-12-18 14:26:09作者: 钟铧若岩
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;
}