Why is the C# compiler giving a runtime exception about this raw query not executing properly when it executes correctly in SQL Server Management Studio?
I'm getting this exception stopping the app at runtime in the C# code below this query:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'GROUP'.'
Goal: Return 3 rows of data as JSON to the ASP.NET controller (controller is already returning hardcoded dummy data, but needs to be able to return this data as JSON eventually).
Original SQL Server procedure (executes without errors in SQL Server Management Studio, see very bottom for data returned by this query):
Select
sum(jobs) as JobCount,avg(price) as avgPrice,
shift,
Convert(varchar(10), date, 120) as date
from
[database_test].[dbo].station
where
grading > 0
and date = '04/21/2017'
and shift in ('1', '2', '3')
and stationid in (select stationid
from [database_test].[dbo].WSConfig
where genmodel = 'C:\stations\Zone.mdb')
group by
date, shift
order by
date;
Equivalent C# / .NET Core code to query the database for this information
//Repository class with injected DbContext (Entity Framework Core way of doing it)
public class DateRepository {
public database_testContext storeDB = null;
public DateRepository(database_testContext storeDB)
{
this.storeDB = storeDB;
}
public void DateRepository(database_testContext dbContext)
{
storeDB = dbContext;
}
// This method is supposed to return 3 rows of data off of a raw SQL query
public IEnumerable<station> ReturnData()
{
// DB querying variable
var context = storeDB;
var testQuery = context.station.FromSql(@"Select sum(jobs) as JobCount,avg(price) as avgPrice,
shift, Convert(varchar(10),date,120) as date from [database_test].[dbo].station
where grading > 0
and date = '04/21/2017'
and shift in ('1','2','3')
and stationid in
(select stationid from [database_test].[dbo].WSConfig where genmodel = 'C:\stations\Zone.mdb')
GROUP BY date,shift
order by date;").ToList().Take(3)
return testQuery;
}
}
This is what is returned by the SQL query in SQL Server Management Studio:
JobCount avgPrice shift date
------------------------------------------
4420 251.25 1 2017-04-21
3253 268.69 2 2017-04-21
4634 256.46 3 2017-04-21