我正在尝试运行一个返回到自定义对象的简单自定义查询,但是,我一直遇到错误而且我不知道出了什么问题。该查询在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; }
}
主要方法:
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();
我得到的错误是:
查询语法无效。近期&#39; *&#39;,第2行,第39栏。
此查询在SQL Server Management Studio中正常运行。
另外,根据这篇文章,我正确地做到了:https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx
答案 0 :(得分:0)
这是EntityFramework查询解析器中的错误。我所能做的就是为你提供一种解决方法(BTW,甚至可以更快地运行):
var query = @"SELECT
ISNULL(SUM(CASE WHEN [Status] = 0 THEN 1 ELSE 0 END),0) as EligibleCredits,
ISNULL(SUM(CASE WHEN [Status] = 1 THEN 1 ELSE 0 END),0) as ReadyForSubmissionCredits,
ISNULL(SUM(CASE WHEN [Status] = 2 THEN 1 ELSE 0 END),0) as RedeemedCredits
FROM MyTable
WHERE UserId = @userId
AND Year(EarnDate) >= Year(getdate()) - @years";
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();
请注意,如果this
是DbContext
的实例,您可以按如下方式简化代码:
var query = @"SELECT
ISNULL(SUM(CASE WHEN [Status] = 0 THEN 1 ELSE 0 END),0) as EligibleCredits,
ISNULL(SUM(CASE WHEN [Status] = 1 THEN 1 ELSE 0 END),0) as ReadyForSubmissionCredits,
ISNULL(SUM(CASE WHEN [Status] = 2 THEN 1 ELSE 0 END),0) as RedeemedCredits
FROM MyTable
WHERE UserId = @p0 -- <== NOTE THE PARAM NAME HERE AND BELOW
AND Year(EarnDate) >= Year(getdate()) - @p1";
return new this.Database.SqlQuery<MyClass>(query, userId, years).FirstOrDefault();
最后一种方法也适用于原始查询。
答案 1 :(得分:0)
ExecuteStoreQuery 为我工作,同样的错误。示例如下:
IList<MyClass> contactList =
(((IObjectContextAdapter) model).ObjectContext.ExecuteStoreQuery<MyClass>(strString))
.ToList<MyClass>();