We want to execute a stored procedure using EF.
Our approach is to provide input parameters dynamically as shown below :
PropertyInfo[] props = search.GetProperties();
foreach (var item in props)
{
object itemValue = item.GetValue(SearchCondition, null);
if (itemValue == null)
parameterList.Add(new SqlParameter(string.Format("@{0}", item.Name), DBNull.Value));
else
parameterList.Add(new SqlParameter(string.Format("@{0}", item.Name), itemValue.ToString()));
}
and here are other common inputs:
parameterList.Add(new SqlParameter("@order", (object)"desc"));
parameterList.Add(new SqlParameter("@Page", page));
parameterList.Add(new SqlParameter("@PageSize", rows));
and also output parameter:
parameterList.Add(new SqlParameter()
{
DbType = DbType.Int32,
ParameterName = "@TotalCount out",
SqlValue = DBNull.Value,
Direction = ParameterDirection.Output
});
and here is execution code (running the stored procedure)
object[] para= parameterList.ToArray<object>();
var records = context.Database.SqlQuery<CustomerInformationReturnedList>(string.Format(@"Exec RTI.RptCustomerInformation {0}", parameters), para).ToList();
When we run it there is an exception that says:
incorrect syntax near int
This is our executed stored procedure in SQL which runs correctly in SQL Server Management Studio:
EXEC @return_value = [RTI].[RptCustomerInformation]
@AccountNumber = NULL,
@CardNumber = NULL,
@CustomerNumber = NULL,
@CustomerType = NULL,
@NationalNumber = NULL,
@Name = NULL,
@FamilyName = NULL,
@IdentityNumber = NULL,
@IdSerial = NULL,
@NationalityType = NULL,
@InhabitancyType = NULL,
@JobType = NULL,
@c13 = NULL,
@CustomerDefined = NULL,
@OpenerBranch = NULL,
@CodePosti = NULL,
@RegisterNumber = NULL,
@order = NULL,
@Page = NULL,
@PageSize = NULL,
@TotalCount = @TotalCount OUTPUT
SELECT @TotalCount as N'@TotalCount'