C#,根据Model生成sql语,并生成sql参数(使用Attribute字段特性)

namespace 根据Model生成Sql
{
    public class KeyAttribute : Attribute
    {
        //注意KeyAttribute  前面key可以随意写但后面要为Attribute
        public bool IsIncrement { get; set; }
    }
}
namespace 根据Model生成Sql
{
   public class TestModel
    {
        //KeyAttribute 这个Key
        //如果 TestAttribute则特性写[Test(IsIncrement = true)]
        [Key(IsIncrement = true)]
        public int ID { get; set; }
        public string Name { get; set; }
        public string QQ { get; set; }
        public string Email { get; set; }      
    }
}
namespace 根据Model生成Sql
{
    public class TestDal
    {
        public void CreateSql2<T>(T model)
        {
            Type type = typeof(T);
            PropertyInfo[] propertyArray = type.GetProperties();
            foreach (PropertyInfo prop in propertyArray)
            {
                //判断是否标有特性
                if (prop.IsDefined(typeof(KeyAttribute), true))
                {
                    KeyAttribute attribute = (KeyAttribute)prop.GetCustomAttributes(typeof(KeyAttribute), true)[0];
                    //判断标的特性的bool
                    if (attribute.IsIncrement)
                    {
                        //where条件去掉p => !p.Name.Equals(prop.Name) 这个特性字段
                        //p => p.Name.Equals(prop.Name)  这样就是只要特性的字段
                        propertyArray = type.GetProperties().Where(p => !p.Name.Equals(prop.Name)).ToArray();
                    }
                }
            }
            string[] strSqlNames = propertyArray.Select(p => $"[{p.Name}]").ToArray();
            string strSqlName = string.Join(",", strSqlNames);
            string[] strSqlValues = propertyArray.Select(P => $"@{P.Name}").ToArray();
            string strSqlValue = string.Join(",", strSqlValues);
            //strSql是创建的Sql语句
            string strSql = "insert into testModel ( " + strSqlName + " ) values (" + strSqlValue + ")";
            //para Sql是参数
            SqlParameter[] para = propertyArray.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.CreateSql2(model);
        }

评论