简体   繁体   中英

Calling a stored-procedure from entity framework with various parameters

I have 3 sprocs named:

  1. RECEIVED
  2. NOTRECEIVED
  3. UPDATESTATUS

RECEIVED and NOTRECEIVED have the following params

@ProductNumber,
@ProductName

UPDATESTATUS has:

@BatchNumber

I have gone ahead and created a method which I use to execute the sproc named UPDATESTATUS . I want to make it flexible so I can call it for all of the sprocs regardless of the params and pass in the sproc name to the method.

The method is as follows:

public async Task<int> ExecuteSproc(SqlParameter[] sqlParameter)
{
   int result = await db.Database.ExecuteSqlCommandAsync("exec UPDATESTATUS @BatchNumber", sqlParameter);

   return result;
}

This is how I called method ExecuteSproc()

SqlParameter[] sqlParameter = new SqlParameter[]
{
   new SqlParameter("@BatchNumber", System.Data.SqlDbType.NVarChar){ Value = batchNumber}
};

int count = await ExecuteSproc(sqlParameter);

Can some tell me how I would achieve this please. I look at this post but the answer suggest I have to specify the param names whereas I am trying to make it a little more generic

You need to pass stored procedure name & parameter in KeyValuePair format.

public List<V> ExecStoredProc<V>(string storedProcedureName, KeyValuePair<string, string>[] parameters)
{
    if (parameters.Any())
    {
        SqlParameter[] sqlParams = patameters.Select(x => new SqlParameter("@" + x.Key, x.Value)).ToArray();
        var result = _context.Database
                .SqlQuery<V>(storedProcedureName + " " + string.Join(" ", patameters.Select(x => "@" + x.Key)), sqlParams)
                .ToList();
        _context.Database.Connection.Close();
        return result;
    }
    else
    {
        var result = _context.Database
                .SqlQuery<V>(storedProcedureName)
                .ToList();
        _context.Database.Connection.Close();
        return result;
    }
}

Execution

var parmas = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("BatchNumber", BatchId.ToString()) };

List<User> list = ExecStoredProc<User>("UPDATESTATUS", parmas);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM