C#反射,泛型實現添加

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Stu s = new Stu() { Id = 1, Name = "cdwc", ImAgePrOc = "fiodowwf" };
            OrmHelper.Add<Stu>(s);
        }

        class OrmHelper
        {
            public static int Add<T>(T t)
            {
                Type t1 = t.GetType();
                PropertyInfo[] ps = t1.GetProperties();
                string  [] values = ps.Where(p => p.Name.ToLower() != "id").Select(p => "'" + p.GetValue(t) + "'").ToArray();
                string str = string.Join(",",values);
                string sql = string.Format("insert into {0} values {1}", t1.Name, str);

                using (SqlConnection scon = new SqlConnection("server=.;uid=sa;pwd=1234;database=Month1230"))
                {
                    SqlCommand scom = new SqlCommand(sql, scon);
                    scon.Open();
                    int i = scom.ExecuteNonQuery();
                    scon.Close();
                    return i;
                
                }

            
            
            }
        
        
        
        }

        class Stu
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string ImAgePrOc { get; set; }

        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章