C#,根据Model生成sql语,并生成sql参数

   public class TestModel
    {
       public int ID { get; set; }
       public string Name { get; set; }
       public string QQ { get; set; }
       public string Email { get; set; }  
    }
    public class TestDal
    {
        public void CreateSql<T>(T model)
        {
            Type type = typeof(T);
            string[] strSqlNames = type.GetProperties().Select(p => $"[{p.Name}]").ToArray();
            //以下是不要ID这个字段的  比如自增列ID  就不能像上名那样写   
            //string[] strSqlNames = type.GetProperties().Where(p => !p.Name.Equals("Id")).Select(p => $"[{p.Name}]").ToArray();
            string strSqlName = string.Join(",", strSqlNames);
            string[] strSqlValues = type.GetProperties().Select(P => $"@{P.Name}").ToArray();
            string strSqlValue = string.Join(",", strSqlValues);
            //  strSql得到的  sql语句为insert into testModel ( [ID],[Name],[QQ],[Email] ) values (@ID,@Name,@QQ,@Email)
           string strSql = "insert into testModel ( " + strSqlName + " ) values (" + strSqlValue + ")";
            //para Sql是参数
            SqlParameter[] para = type.GetProperties().Select(p => new SqlParameter($"@{p.Name}", p.GetValue(model, null))).ToArray();
        }
     }
      //这主方法的调用 
       private void button1_Click(object sender, EventArgs e)
        {
            TestDal dal = new TestDal();
            TestModel model = new TestModel()
            {
                ID = 10001,
                Name = "罗分明",
                QQ = "78630559",
                Email = "78630559@qq.com"
            };
            dal.CreateSql(model);
        }

评论