2

I have a big nasty SQL query to run in asp.net mvc 5, it's supposed to return a non-db-table object, and needs to be parameterized.

viz.

context.Database.SqlQuery<MyObject>("select a, b from table where a = @par")

where I can pass in the value of @par as a parameter

class MyObject {
  public a {get;set;}
  public b {get;set;}
}

For whatever reason the msdn docs assume that one cannot possibly want to execute any but the simplest of queries... https://msdn.microsoft.com/en-us/data/jj592907.aspx

2 Answers 2

4

Given:

var myPar = 1;

To use a parameter, try:

context.Database.SqlQuery<MyObject>("select a, b from table where a = @par", new SqlParameter("par", myPar));

Or:

context.Database.SqlQuery<MyObject>("select a, b from table where a = {0}", myPar);
Sign up to request clarification or add additional context in comments.

Comments

0

I prefer not to use SQL select strings to avoid potential SQL injection attacks. You can do this through Linq syntax:

 context.Database.table
     .Where(x => x.a == myPar)
     .Select(x => new MyObject { a = x.a, b = x.b });

Comments

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.