我的查询中的select语句出现问题。此sql查询在SqlServer Management Studio中工作并选择所请求的数据但在我的类中它给出了一个错误“查询语法无效。近期'*',第9行,第47列。”取出LastPostBy,LastPostDate,LastPostTitle之后我的From Forums F子句中的另一个错误我在LastPostTitle中也遇到错误,但我说它在SQLServer Management Studio中有效。我最初试图做一个“Exec sproc_Forums_GetForums”存储过程并且这不起作用这是我第一次尝试在Entities中使用这种方法。 我想要做的就是获取论坛并显示来自名为论坛和帖子的两个表的信息
public List<Forum> GetForums()
{
List<Forum> forums = null;
using (EntityConnection conn = new EntityConnection("name=CMSEntities"))
{
conn.Open();
string query = @"
SELECT ForumGroup = (
CASE WHEN ParentID IS NOT NULL THEN
(SELECT Title FROM Forums WHERE ForumID = F.ParentID)
ELSE
(SELECT Title FROM Forums WHERE ParentID IS NULL)
END),
F.Title, F.Description,
ThreadCount = (SELECT COUNT(*) FROM Posts P WHERE P.ForumID = F.ForumID),
LastPostBy = (SELECT TOP 1 AddedBy FROM Posts P WHERE P.ForumID = F.ForumID ORDER BY P.PostID DESC),
LastPostDate = (SELECT TOP 1 AddedDate FROM Posts P WHERE P.ForumID = F.ForumID ORDER BY P.PostID DESC),
LastPostTitle = (SELECT TOP 1 Title FROM Posts P WHERE P.ForumID = F.ForumID ORDER BY P.PostID DESC)
FROM Forums F WHERE ParentID IS NOT NULL
ORDER BY Title
";
EntityCommand cmd = new EntityCommand(query, conn);
using (EntityDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
Forum forum = new Forum(
(int)reader["ForumID"],
"",
DateTime.Now,
reader["Title"].ToString(),
reader["Description"].ToString(),
0,
false,
null,
null,
null,
true,
reader["ForumGroup"].ToString(),
(int)reader["ThreadCount"],
reader["LastPostBy"].ToString(),
(DateTime)reader["LastPostDate"],
reader["LastPostTitle"].ToString());
forums.Add(forum);
}
return forums;
}
}
}
}
答案 0 :(得分:8)
这不是有效的ESQL查询。您无法在SQL管理中进行SQL查询并将其作为ESQL执行。 ESQL是不同的查询语言,具有自己的语法,它接近于SQL但仍然存在差异,因为它不查询数据库而是实体模型。例如,ESQL中的简单查询如下所示:
SELECT VALUE Entity FROM Namespace.Entities AS Entity WHERE Entity.SomeField = 10
您是否看到了常见SQL的区别?
使用EntityCommand
执行SQL查询或SqlCommand
,而不是使用ESQL和ObjectContext.ExecuteStoreQuery
。