我的查詢中的select語句有問題。這個sql查詢在SqlServer Management Studio中工作,並選擇了請求的數據,但在我的類中,它給了我一個錯誤「查詢語法無效。近期'*',第9行,第47列。那麼我的From論文F子句中的另一個錯誤就是在取出LastPostBy,LastPostDate和LastPostTitle之後,我也在LastPostTitle中發生錯誤,但正如我所說的那樣,它在SQLServer Management Studio中起作用。我最初試圖做一個「Exec sproc_Forums_GetForums」存儲過程,並沒有工作,這是我第一次嘗試在實體中使用這種方法。 我所有的查詢假設做的就是一個論壇,並從兩個表中顯示的信息命名論壇和帖子EntityCommand SQL錯誤
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;
}
}
}
}
這裏有個建議:使用SQL Server Profiler查看發送給SQL Server的確切查詢是什麼。 – Beatles1692 2012-02-05 08:45:18
你如何使用SQL Server Profiler和VS2010在哪裏 – ONYX 2012-02-05 09:00:55
打開你的sql管理工作室,tools-> profiler :) – 2012-02-05 09:19:45