C# 自动查询字符串

C# automate query string

我有一个 MVC-Razor 项目,我有义务在不使用 ORM 的情况下完成它。我只使用 SQL 命令,在数据库控制器的 add(model) 方法中,我以这种格式执行查询字符串命令:

string queryString =
                "INSERT INTO USERS VALUES(@EMAIL,@PAIS,@IDIOMA,@CODPROMO,@NOMBREUSU"+
                ",@PASS,@PIN,@TRATAMIENTO,@NOMBREPERS,@APELLIDOS,@FECHANAC,@DIRECCION,@NUMPISO"+
                ",@CP,@CIUDAD,@NIF,@NUMMOVIL,@SUBSCRIBIR,@CONDICIONES,@PRIVACIDAD)";

如您所见,table 中有很多参数要插入。然后,我必须 link 那些带有 command.Parameters.AddWithValue("@EMAIL",socio.Mail);

的@parameters

有没有更快的方法来完成所有这些(也许是更动态的东西?)而无需所有这些写作?

So any faster way to do this without all of that writing?

是的,如果这是您必须做的,那么请考虑重构您的 SQL 代码并将其拉入 stored procedure(SP) 并在您的代码中调用该 SP。如果要发送结构化数据,也可以考虑使用 table 类型变量。

这是构建查询字符串的反射的快速示例。这个想法是让 class 反映 table 的列。以下代码可用于为任何数据模型构建插入 class。它将构建插入语句并填写参数,然后执行该语句。

    public static void GenericSqlInsert(string connectionString, string table, Object model)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string commandText = "Insert into " + table + "Values(";
            SqlCommand command = new SqlCommand();
            PropertyInfo[] properties = model.GetType().GetProperties();

            foreach (PropertyInfo property in properties)
            {
                commandText += "@" + property.Name + ",";
                command.Parameters.AddWithValue("@" + property.Name, property.GetValue(model));
            }
            commandText = commandText.TrimEnd(',');
            commandText += ") ";

            try
            {
                command.Connection = connection;
                command.CommandText = commandText;

                connection.Open();

                Int32 rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine("RowsAffected: {0}", rowsAffected);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

我不知道我是否会推荐这种方法,但它是一种有趣的反射用法。

已编辑以反映 Alexei Levenkov 的建议

编辑以使函数更通用