如何结合使用 Native SQL 和 Entity Framework、ExecuteStoreQuery 获取记录数?

How to get a record count using Native SQL in conjunction with Entity Framework, ExecuteStoreQuery?

我正在使用 MVC3。 Asp.Net4.5,EF6,SQL服务器 2008

我需要使用本机 SQL 从 table 中获取满足特定条件的记录数。

我相信我需要 ExecuteStoreQuery。我已经尝试了以下代码,但得到了转换异常。

int RecordCount = (int)db.ExecuteStoreQuery<Int32>("select count(*) from myTable where RecordType = '{0}' and ParentId={1}", "MyRecordType", 1);

毫无疑问,有些愚蠢的代码错误。 Guidance/Correction 将不胜感激。

谢谢。

这是来自 Microsoft 的 ado.net 示例。 MS Example

这是一个 C# 示例

    static public int AddProductCategory(string newName, string connString)
    {
        Int32 rowCount = 0;
        string sql = "select count(*) from myTable where RecordType = '@recordType' and ParentId=@parentid;";
        using (SqlConnection conn = new SqlConnection(connString))
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.Add("@recordType", SqlDbType.VarChar);
            cmd.Parameters["@recordType"].Value = "MyRecordType";
            cmd.Parameters.Add("@parentid", SqlDbType.Int);
            cmd.Parameters["@parentid"].Value = 1;
            try
            {
                conn.Open();
                rowCount = (Int32)cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        return (int)rowCount;
    }