我正在使用MVC3。 Asp.Net 4.5,EF6,SQL Server 2008
我需要使用Native SQL从满足特定条件的表中获取记录数。
我相信我需要ExecuteStoreQuery。我尝试了以下代码,但获得了强制转换异常。
int RecordCount = (int)db.ExecuteStoreQuery<Int32>("select count(*) from myTable where RecordType = '{0}' and ParentId={1}", "MyRecordType", 1);
毫无疑问,有些愚蠢的代码错误。指导/更正将不胜感激。
感谢。
答案 0 :(得分:1)
以下是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;
}