Entity Framework 错误 - 查询语法无效

Entity Framework Error - The query syntax is not valid

我正在尝试 运行 返回到自定义对象的简单自定义查询,但是,我一直 运行ning 出错,我不知道哪里出了问题。查询 运行 在 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();

我得到的错误是:

The query syntax is not valid. Near term '*', line 2, column 39.

这个查询 运行 在 SQL Server Management Studio 中没问题。

另外,根据这篇文章,我做的是正确的:https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx

这是 EntityFramework 查询解析器中的错误。我所能做的就是为您提供一个解决方法(顺便说一句,甚至可能 运行 更快):

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();

请注意,如果 thisDbContext 的实例,您可以简化代码如下:

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();

最后一种方法也适用于您的原始查询

ExecuteStoreQuery 为我工作,同样的错误。示例如下:

IList<MyClass> contactList =
            (((IObjectContextAdapter) model).ObjectContext.ExecuteStoreQuery<MyClass>(strString))
            .ToList<MyClass>();