简体   繁体   English

使用各种参数从实体框架调用存储过程

[英]Calling a stored-procedure from entity framework with various parameters

I have 3 sprocs named:我有3个sprocs命名为:

  1. RECEIVED已收到
  2. NOTRECEIVED没收到
  3. UPDATESTATUS更新状态

RECEIVED and NOTRECEIVED have the following params RECEIVEDNOTRECEIVED具有以下params

@ProductNumber,
@ProductName

UPDATESTATUS has: UPDATESTATUS有:

@BatchNumber

I have gone ahead and created a method which I use to execute the sproc named UPDATESTATUS .我已经创建了一个方法,用于执行名为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.我想让它变得灵活,以便我可以为所有 sproc 调用它,而不管参数如何,并将 sproc 名称传递给方法。

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()这就是我调用方法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.您需要以 KeyValuePair 格式传递存储过程名称和参数。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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