youmingkuang
     public T Get<T>(int id)
        {

            Type type = typeof(T);
            string columnStrings = string.Join(",", type.GetProperties().Select(p=>string.Format("[{0}]")));

            string sql = string.Format("select {0} from  [{1}] where id={2}", columnStrings,type.Name,id);


            return default(T);
        }

 完整例子

  public T Get<T>(int id)
        {

            Type type = typeof(T);
            string columnStrings = string.Join(",", type.GetProperties().Select(p=>string.Format("[{0}]")));

            string sql = string.Format("select {0} from  [{1}] where id={2}", columnStrings,type.Name,id);

            object t = Activator.CreateInstance(type);
            using (SqlConnection conn = new SqlConnection("链接字符串"))
            {
                SqlCommand com = new SqlCommand(sql,conn);
                conn.Open();
                SqlDataReader reader = com.ExecuteReader();
                if (reader.Read())
                {
                    foreach (var item in type.GetProperties())
                    {
                        item.SetValue(t,reader[item.Name]);
                    }
                }

            }

            return (T)t;
        }

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
  • 2022-02-16
  • 2022-12-23
  • 2021-10-24
  • 2022-01-28
猜你喜欢
  • 2022-01-20
  • 2022-01-04
  • 2022-02-11
  • 2022-01-15
  • 2022-12-23
  • 2022-12-23
  • 2021-04-22
相关资源
相似解决方案