c# - Is there a less torturous way to INSERT INTO? -


if want insert multiple objects sql server db seems have this:

        using (var command = new sqlcommand(@"insert table1 (             param_1,             param_2,             param_3,             ...             )             values (             @param1,             @param2,             @param3,             ...             )",conn))             {               command.params.add("@param1",...);               command.params.add("@param2",...);               command.params.add("@param3",...);               ...               foreach(var o in objects)               {                 command.params["@param1"].value = o.param1;                 command.params["@param2"].value = o.param2;                 command.params["@param3"].value = o.param3;                 ...                 command.executenonquery();               }             } 

just putting has me pulling hair out, , have table 28 fields. have write out long list 4 separate times, trivial differences (db field names may use different naming convention). seems crazy; there shorter way?

entity framework isn't option me here would've been first choice, have roll code.

if totally against using external libraries, how this?

void insert (dictionary <string, sqltype> cols, object [] objects) {     string colnames = string.join (",", cols.keys);     string paramnames = string.join (",", cols.keys.select (c=>"@"+c));      using (var command = new sqlcommand(@"insert table1 (" + colnames +             ") values (" + paramnames + ")",conn))     {           foreach (var col in cols)           {              command.params.add("@" + col.key, col.value);           }            foreach(var o in objects)           {             // here have list them unless             // object o dictionary<string, object> or datarow.             command.params["@param1"].value = o.param1;             command.params["@param2"].value = o.param2;             command.params["@param3"].value = o.param3;             ...             command.executenonquery();           }      } } 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -