代码改变世界

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

2023-12-18 14:21  钟铧若岩  阅读(39)  评论(0编辑  收藏  举报
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;
}