Вопрос

In my code I am repeating code blocks like this all the time:

var returnData = MyDb.ExecuteDataSet(
    MyDb.GetStoredProcCommand("MyTable_Insert", columnOne, columnTwo, columnThree),
    transaction
);

var returnId = (int)returnData.Tables[0].Rows[0]["INSERTED_ID"];

This seems to me to be a fairly large block of code to be repeating so many times, but I can't work out how to generalise it into a method because the number of arguments is different to each stored procedure.

The obvious solution (to me) is to pass my parameters through to the function in an array and then expand them to call GetStoredProcCommand, but I can't find a way to do this:

private int CallStoredProcedure(string procName, List<dynamic> parameterValues) {
    ..
    MyDb.GetStoredProcCommand(procName, expand parameterValues);
    // ERROR: Obviously "expand" doesn't exist
    ..
}

I could use the longer-winded way passing parameters using AddInParameter, but then I would need to pass type information along with the parameter values:

private int CallStoredProcedure(string procName, IDictionary<DbType, IDictionary<string, string>> paramsKeyValuesByType) {
    ..
    MyDb.AddInParameter(myProcCommand, param.Value.Key, param.Key, param.Value.Value);
    ..
}

But then I'd have to construct the IDictionary object before calling the method which would be even more long-winded than how I was originally calling the procedure.

Can anyone think of an elegant solution to this?

Это было полезно?

Решение

You can use the params keyword:

private int CallStoredProcedure(string procName, params object[] parameterValues) {
    ..
    MyDb.GetStoredProcCommand(procName, parameterValues);
    ..
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top