EntityCommand SQL Error

本文关键字:Error SQL EntityCommand | 更新日期: 2023-09-27 18:22:25

我的查询中的select语句有问题。这个sql查询在SqlServer Management Studio中工作,并选择所请求的数据,但在我的类中,它给了我一个错误"查询语法无效。在第47列第9行第'*'项附近。"然后在我的From Forums F子句中出现另一个错误,即删除LastPostBy、LastPostDate和LastPostTitle之后,我在LastPostTitle中也遇到了一个错误。但正如我所说,它在SqlServer Management Studio中运行。我最初尝试做一个"Exec sproc_Forums_GetForums"存储过程,但没有成功——这是我第一次尝试在实体中使用这种方法。我想做的所有查询都是获取一个论坛,并显示来自两个名为Forums和Posts 的表的信息

    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;
            }
        }
    }
}

EntityCommand SQL Error

这不是有效的ESQL查询。您不能在SQL管理中进行SQL查询并将其作为ESQL执行。ESQL是一种不同的查询语言,它有自己的语法,与SQL相近,但由于它不查询数据库,而是查询实体模型,因此仍然存在差异。例如,ESQL中的简单查询如下:

SELECT VALUE Entity FROM Namespace.Entities AS Entity WHERE Entity.SomeField = 10

你看到普通SQL的区别了吗?

不使用ESQL和EntityCommand,而是使用SqlCommand执行SQL查询或ObjectContext.ExecuteStoreQuery