2
private int GetId(int userId, int companyId){
    string query = String.Format("SELECT Id FROM MyTable WHERE UserId = {0} AND CompanyId = {1}", userId, companyId);
    return _db.ExecuteSqlCommand(query);
}

I can run the query via Microsoft's SQL Management Studio and it returns 15. Every time I execute it within the code it returns -1.

MSDN API States:

Return Value

Type: System.Int32

The result returned by the database after executing the command.

The description is very vaugue, and I think how I am using it should be working. How can I manipulate the query to return 15, or is that not possible? If not, does anyone have any recommendations?

Community
  • 1
  • 1
James Madison
  • 337
  • 1
  • 4
  • 17
  • this looks like you want to execute this select as a scalar, rather than as just a command that does not return anything. look at this question: http://stackoverflow.com/questions/14368505/calling-scalar-function-from-c-sharp-using-entity-framework-4-0-edmx – Nathan Tregillus Jul 07 '15 at 15:24

1 Answers1

1

When executing a command that returns data, such as a 'SELECT' statement, you should consider using the SqlQuery method. ExecuteSqlQuery is generally regarded as a DDL/DML command for statements like an 'UPDATE' that do not return data.

Additionally, you should always parameterize a query such as this. As written, it's vulnerable to SQL Injection attacks.

David W
  • 10,062
  • 34
  • 60