泛型+反射 实现泛型向数据库插入信息类 并返回插入数据的Id值

时间:2021-12-27 21:43:03
static string conStr = @"server=.;database=a;uid=sa;pwd=a;";
/// <summary>
        /// ExecuteScalar
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="ps">SqlParameter</param>
        /// <returns>查询结果表中最左上角单元格的数据</returns>
        private static object ExecuteScalar(string sql, params SqlParameter[] ps)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {

                    cmd.Parameters.AddRange(ps);
                    con.Open();
                    return cmd.ExecuteScalar();
                }
            }
        }


//新增一条信息 并返回插入后该数据的Id
        public static int InsertModel<T>(T t)
            where T : BaseModel, new()
        {

            //获取类型
            Type type=typeof(T);
            //获得字段列表
           PropertyInfo[] Prop= type.GetProperties();
            //拼接字符串
            string sql = string.Format("insert into [{0}]({1}) values({2});select @@identity",
                type.Name,
                string.Join(",",Prop.Where(s=>s.Name!="Id").Select(s=>string.Format("[{0}]",s.Name))),
                string.Join(",", Prop.Where(s => s.Name != "Id").Select(s => string.Format("@{0}", s.Name)))
                );

            SqlParameter[] ps = Prop.Where(s => s.Name != "Id").Select(s => new SqlParameter(string.Format("@{0}",s.Name),s.GetValue(t,null)??DBNull.Value)).ToArray();

            return int.Parse(ExecuteScalar(sql,ps).ToString());
        }