277

I have a stored procedure that has three parameters and I've been trying to use the following to return the results:

context.Database.SqlQuery<myEntityType>("mySpName", param1, param2, param3);

At first I tried using SqlParameter objects as the params but this didn't work and threw a SqlException with the following message:

Procedure or function 'mySpName' expects parameter '@param1', which was not supplied.

So my question is how you can use this method with a stored procedure that expects parameters?

Thanks.

2
  • What version of SQL Server are you using? I'm having trouble with code that works on 2008 in compat (90) mode, but when i run it against 2005 it fails with a syntax error.
    – Gats
    Feb 2, 2011 at 17:18
  • 4
    @Gats - I had the same issue w/ SQL 2005. Add "EXEC" before the stored procedure name. I posted this info here for future reference: stackoverflow.com/questions/6403930/…
    – Dan Mork
    Jun 19, 2011 at 17:26

10 Answers 10

423

You should supply the SqlParameter instances in the following way:

context.Database.SqlQuery<myEntityType>(
    "mySpName @param1, @param2, @param3",
    new SqlParameter("param1", param1),
    new SqlParameter("param2", param2),
    new SqlParameter("param3", param3)
);
11
  • 3
    How would you make this method work with nullable types? I tried this with nullable decimals, but when the decimals are null I get errors saying parameter is missing. However, the method below mentioned by @DanMork works find. Mar 15, 2012 at 20:11
  • 2
    Does passing DbNull.Value instead of nulls solve the problem?
    – Alireza
    Sep 5, 2012 at 11:11
  • 32
    You can also use the \@p# syntax to avoid using SqlParameter as in context.Database.SqlQuery<myEntityType("mySpName \@p0, \@p1, \@p2", param1, param2, param3). Source: msdn.microsoft.com/en-US/data/jj592907. (Note: had to use \@ to avoid user notifications, should be read without the backslash.)
    – Marco
    Nov 1, 2012 at 22:17
  • 3
    If you are using DateTime parameters, you need to specify the parameter type too, not only name and value. For example: dbContext.Database.SqlQuery<Invoice>("spGetInvoices @dateFrom, @dateTo", new SqlParameter { ParameterName = "dateFrom", SqlDbType = SqlDbType.DateTime, Value = startDate }, new SqlParameter { ParameterName = "dateTo", SqlDbType = SqlDbType.DateTime, Value = endDate }); Another important thing is to respect the order of the parameters. Jul 21, 2014 at 17:56
  • can you kindly check what I am doing wrong I have follow you guidline but no effect at all stackoverflow.com/questions/27926598/…
    – K.Z
    Jan 13, 2015 at 20:31
134

Also, you can use the "sql" parameter as a format specifier:

context.Database.SqlQuery<MyEntityType>("mySpName @param1 = {0}", param1)
9
  • Had to up-vote this. While it wasn't accepted as the answer, its a much easier to write solution than the one selected as answer.
    – Nikkoli
    Oct 2, 2012 at 18:43
  • 10
    This syntax concerns me a little bit. Would it be susceptible to SQL injection? I would assume EF is running "EXEC mySpName @Param1 = ", and it would be possible to send "x' GO [malicious script]" and cause some problems? Oct 5, 2012 at 17:45
  • 10
    @TomHalladay no risk of SQL injection - the method will still quote and escape the parameters based on their type, the same as the @ style params. So for a string parameter you would use "SELECT * FROM Users WHERE email={0}" without quotes in your statement.
    – Ross McNab
    Feb 14, 2013 at 11:52
  • in my case we have lots of optional parameters for SP and did not work calls with SqlParameters but this format do the trick, just had to add 'EXEC' in the beginning. Thanks.
    – Onur Topal
    Apr 10, 2013 at 12:23
  • 1
    This answer is useful if you have to specify parameters to a proc with optional parameters. Example that doesn't work: ProcName @optionalParam1 = @opVal1, @optionalParam2 = @opVal2 Example that does work: ProcName @optionalParam1 = {0}, @optionalParam2 = {1} Dec 3, 2014 at 17:44
72

This solution is (only) for SQL Server 2005

You guys are lifesavers, but as @Dan Mork said, you need to add EXEC to the mix. What was tripping me up was:

  • 'EXEC ' before the Proc Name
  • Commas in between Params
  • Chopping off '@' on the Param Definitions (not sure that bit is required though).

:

context.Database.SqlQuery<EntityType>(
    "EXEC ProcName @param1, @param2", 
    new SqlParameter("param1", param1), 
    new SqlParameter("param2", param2)
);
11
  • 23
    +1. Neither of the higher voted answers include exec, but I can confirm that I get an exception if I omit it. Oct 5, 2012 at 13:46
  • Thank you, I was getting an error, added EXEC and error is gone. The weird part was if i did context.Database.SqlQuery<EntityType>("ProcName '" + param1 + "','" + param2 + "'"); it worked, but if I added parameters it didn't work until I added the EXEC keyword.
    – Solmead
    Jan 10, 2014 at 21:58
  • 2
    FYI: I do not require the exec keyword. +1 for the removal of the @ on the params, that always messes me up. Jan 30, 2014 at 17:46
  • +1, I was missing EXEC and kept getting SqlExceptions with message: Incorrect syntax near 'procName'.
    – A. Murray
    Feb 13, 2014 at 14:39
  • 1
    @Ziggler are you on 2005 or newer? The EXEC keyword has mainly been an issue for those of us going against 2005. Mar 31, 2015 at 17:38
18
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
        new object[] { param1, param2, param3 });

Or

using (var context = new MyDataContext())
{
    return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
            new object[] { param1, param2, param3 })
        .ToList();
}

Or

using (var context = new MyDataContext())
{
    object[] parameters =  { param1, param2, param3 };

    return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
            parameters)
        .ToList();
}

Or

using (var context = new MyDataContext())
{  
    return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
            param1, param2, param3)
        .ToList();
}
3
  • it is working for me for Assembly EntityFramework.dll, v4.4.0.0
    – Thulasiram
    Oct 18, 2012 at 14:37
  • 2
    if you are using using(var context = new MyDataContext()) then .ToList() is mandatory.
    – Thulasiram
    Oct 18, 2012 at 14:41
  • I spent some good amount of time to discover that .ToList() is mandatory to get correct result set.
    – Halim
    Jun 2, 2016 at 7:48
11

Most answers are brittle because they rely on the order of the SP's parameters. Better to name the Stored Proc's params and give parameterized values to those.

In order to use Named params when calling your SP, without worrying about the order of parameters

Using SQL Server named parameters with ExecuteStoreQuery and ExecuteStoreCommand

Describes the best approach. Better than Dan Mork's answer here.

  • Doesn't rely on concatenating strings, and doesn't rely on the order of parameters defined in the SP.

E.g.:

var cmdText = "[DoStuff] @Name = @name_param, @Age = @age_param";
var sqlParams = new[]{
   new SqlParameter("name_param", "Josh"),
   new SqlParameter("age_param", 45)
};

context.Database.SqlQuery<myEntityType>(cmdText, sqlParams)
4
  • It seems "params" is a reserved keyword, so I don't think you can use it like that. Otherwise this was a helpful answer for me. Thanks!
    – ooXei1sh
    Apr 11, 2018 at 15:19
  • @ooXei1sh - fixed, using sqlParams variable Dec 18, 2018 at 22:41
  • you can prefix it with @ to use a reserved word, but you really shouldn't
    – StingyJack
    Feb 7, 2019 at 17:09
  • 1
    Thanks, every other answer require parameters to be in the same sequence. Jan 14, 2021 at 9:02
7
db.Database.SqlQuery<myEntityType>("exec GetNewSeqOfFoodServing @p0,@p1,@p2 ", foods_WEIGHT.NDB_No, HLP.CuntryID, HLP.ClientID).Single()

or

db.Database.SqlQuery<myEntityType>(
    "exec GetNewSeqOfFoodServing @param1, @param2", 
    new SqlParameter("param1", param1), 
    new SqlParameter("param2", param2)
);

or

var cmdText = "exec [DoStuff] @Name = @name_param, @Age = @age_param";
var @params = new[]{
   new SqlParameter("name_param", "Josh"),
   new SqlParameter("age_param", 45)
};

db.Database.SqlQuery<myEntityType>(cmdText, @params)

or

db.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 }).ToList();
3

I use this method:

var results = this.Database.SqlQuery<yourEntity>("EXEC [ent].[GetNextExportJob] {0}", ProcessorID);

I like it because I just drop in Guids and Datetimes and SqlQuery performs all the formatting for me.

1

@Tom Halladay's answer is correct with the mention that you shopuld also check for null values and send DbNullable if params are null as you would get an exception like

The parameterized query '...' expects the parameter '@parameterName', which was not supplied.

Something like this helped me

public static object GetDBNullOrValue<T>(this T val)
{
    bool isDbNull = true;
    Type t = typeof(T);

    if (Nullable.GetUnderlyingType(t) != null)
        isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);
    else if (t.IsValueType)
        isDbNull = false;
    else
        isDbNull = val == null;

    return isDbNull ? DBNull.Value : (object) val;
}

(credit for the method goes to https://stackoverflow.com/users/284240/tim-schmelter)

Then use it like:

new SqlParameter("@parameterName", parameter.GetValueOrDbNull())

or another solution, more simple, but not generic would be:

new SqlParameter("@parameterName", parameter??(object)DBNull.Value)
1

I did mine with EF 6.x like this:

using(var db = new ProFormDbContext())
            {
                var Action = 1; 
                var xNTID = "A239333";

                var userPlan = db.Database.SqlQuery<UserPlan>(
                "AD.usp_UserPlanInfo @Action, @NTID", //, @HPID",
                new SqlParameter("Action", Action),
                new SqlParameter("NTID", xNTID)).ToList();


            }

Don't double up on sqlparameter some people get burned doing this to their variable

var Action = new SqlParameter("@Action", 1);  // Don't do this, as it is set below already.
0

I had the same error message when I was working with calling a stored procedure that takes two input parameters and returns 3 values using SELECT statement and I solved the issue like below in EF Code First Approach

 SqlParameter @TableName = new SqlParameter()
        {
            ParameterName = "@TableName",
            DbType = DbType.String,
            Value = "Trans"
        };

SqlParameter @FieldName = new SqlParameter()
        {
            ParameterName = "@FieldName",
            DbType = DbType.String,
            Value = "HLTransNbr"
        };


object[] parameters = new object[] { @TableName, @FieldName };

List<Sample> x = this.Database.SqlQuery<Sample>("EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", parameters).ToList();


public class Sample
{
    public string TableName { get; set; }
    public string FieldName { get; set; }
    public int NextNum { get; set; }
}

UPDATE: It looks like with SQL SERVER 2005 missing EXEC keyword is creating problem. So to allow it to work with all SQL SERVER versions I updated my answer and added EXEC in below line

 List<Sample> x = this.Database.SqlQuery<Sample>(" EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", param).ToList();
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.