3

I am trying to follow this tutorial:

http://blogs.msdn.com/b/diego/archive/2012/01/10/how-to-execute-stored-procedures-sqlquery-in-the-dbcontext-api.aspx

but can't seem to to access this method, it will not show up in intelli-sense

context.Database.SqlQuery

I am using the following code but can't seem to access the SqlQuery method:

using(Entities db = new Entities())
{    
}
3
  • If you try to compile it, do you get any error message? Commented Aug 3, 2012 at 8:28
  • What version of EF are you using, ie is your context (Entities) a DbContext or an objectcontext Commented Aug 3, 2012 at 8:35
  • I am using ObjectContext Commented Aug 3, 2012 at 9:13

2 Answers 2

4

The method you have described is valid for executing SQL vs a DbContext version of EF. (DbContext is used for Code First and is also available for model first but you need to do a little setup). However in your example it should be the following.

using(Entities db = new Entities())
{   
    db.Database.SqlQuery(....);
}

If you are using OOB model first (ie edmx), you are probably using an ObjectContext, in which case you will need to perform the following:

using(Entities db = new Entities())
{   
    db.ExecuteStoreQuery<ReturnType>("...");
}

See: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx

Sign up to request clarification or add additional context in comments.

2 Comments

Does ExecuteStoreQuery allow the query to return an output value?
probably but im not too sure of the exact syntax. If your output value is a single int or string, putting that into the generic argument will probably give you the result you are after, although i havent tried this. Alternatly you could create a POCO class to match the response type and put that into the generic. There may also be a version returning object.
0
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();
}

1 Comment

it is working for me for Assembly EntityFramework.dll, v4.4.0.0. if you are using using(var context = new MyDataContext()) then .ToList() is mandatory.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.