简体   繁体   中英

Database call throwing unexpected error in C#

I have written the following method to get a list of objects from database:

public IEnumerable<ProductDBKey6> AssignProductKey6 (string strProdList)
        {
            List<ProductDBKey6> lstProdDBKey6 = new List<ProductDBKey6>();

            // Create the parameters collection
            var parameters = new Collection<SqlParameter>();

            // Add each parameter.  Entity will not work without all params in the correct order            
            SqlParameter param = StoredProcedureParameterBuilder.StringParam("@ProductID", strProdList, -1);

            int? tempTimeout = this.Database.CommandTimeout;
            this.Database.CommandTimeout = 300;
            lstProdDBKey6 = this.Database.SqlQuery<ProductDBKey6>("spc.FindProductDBKeyForID", param).ToList();
            this.Database.CommandTimeout = tempTimeout;

            return lstProdDBKey6;
        }

But I am receiving the error that @ProductID parameter is not supplied. Following is the code written in StoredProcedureParameterBuilder class:

internal static class StoredProcedureParameterBuilder
    {
        internal static SqlParameter StringParam(string paramName, string paramValue, int paramSize)
        {
            SqlParameter outParam = new SqlParameter
            {
                ParameterName = paramName,
                SqlDbType = System.Data.SqlDbType.VarChar,
                Direction = System.Data.ParameterDirection.Input,
                Size = paramSize
            };

            if (string.IsNullOrEmpty(paramValue))
            {
                outParam.Value = DBNull.Value;
            }
            else
            {
                outParam.Value = paramValue;
            }

            return outParam;
        }
    }

My stored procedure accepts only one parameter @ProductID. Following is the Stored Procedure declaration:

ALTER PROCEDURE [spc].[FindProductDBKeyForID] (
        @ProductID          VARCHAR(MAX)
)

Please help how to resolve the error.

Instead of this line:

lstProdDBKey6 =
      this
      .Database.SqlQuery<ProductDBKey6>("spc.FindProductDBKeyForID", param)
      .ToList();

Try this:

lstProdDBKey6 =
      this
      .Database.SqlQuery<ProductDBKey6>("exec spc.FindProductDBKeyForID @ProductID", param)
      .ToList();

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