I am trying to run a simple custom query that is returned into a custom object, however, I keep running into an error and I have no idea what is wrong. The query runs just fine in SQL Server Management Studio.
public class MyClass
{
public Nullable<int> EligibleCredits { get; set;}
public Nullable<int> ReadyForSubmissionCredits { get; set; }
public Nullable<int> RedeemedCredits { get; set; }
}
Main Method:
var query = @"SELECT
(select count(*) from MyTable where UserId = @userId and [Status] = 0 and Year(EarnDate) >= (select Year(getdate()) -@years)) as EligibleCredits,
(select count(*) from MyTable where UserId = @userId and [Status] = 1 and Year(EarnDate) >= (select Year(getdate()) -@years)) as ReadyForSubmissionCredits,
(select count(*) from MyTable where UserId = @userId and [Status] = 2 and Year(EarnDate) >= (select Year(getdate()) -@years)) as RedeemedCredits";
var objectQuery = new ObjectQuery<MyClass>(query, ((IObjectContextAdapter)this).ObjectContext);
objectQuery.Parameters.Add(new ObjectParameter("userId", userId));
objectQuery.Parameters.Add(new ObjectParameter("years", years));
return objectQuery.FirstOrDefault();
The error that I get is:
The query syntax is not valid. Near term '*', line 2, column 39.
This query runs fine in SQL Server Management Studio.
Also, according to this article, I'm doing it correctly: https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx
userIdandyearsints? Are theynullable?select count(UserId), CASE WHEN [Status] = 0 THEN 'EligibleCredits' WHEN [Status] = 1 THEN 'ReadyForSubmissionCredits' WHEN [Status] = 2 THEN 'RedeemedCredits' END AS CreditType from MyTable where UserId = @userId and [Status] IN (0,1,2) and Year(EarnDate) >= (select Year(getdate()) -@years)) GROUP BY [Status].ObjectContextAPIs, use the EF6 preferredcontext.Database.SqlQuery<MyClass>(...)- look at the help how to specify parameters.