我需要通过 linq 操作执行存储过程来访问数据。请看下面我的代码。告诉我哪里出错了。
public int ID { get; set; }
public string CategoryName { get; set; }
public static void GetCategory()
{
string connectionString = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
var query = "EXEC SP_GET_ALL_CATEGORY"; // my stored procedure which is in SQL server
using (DataContext dc = new DataContext(connectionString))
{
if (dc.DatabaseExists())
{
var _vGetCategory = dc.ExecuteQuery<category>(string.Format(query, 1, "null")).ToList(); // execution should only through Stored Procedures
for (int i = 0; i < _vGetCategory.Count; i++)
{
string _strName = _vGetCategory[i].CategoryName;
}
}
}
我的例外:
System.InvalidCastException was unhandled by user code
Message=Specified cast is not valid.
Source=System.Data
StackTrace:
at System.Data.SqlClient.SqlBuffer.get_Int32()
at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)
at Read_category(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at category.GetCategory() in d:\Shankar\sample\LinqtoSql\App_Code\category.cs:line 28
at _Default.Page_Load(Object sender, EventArgs e) in d:\Shankar\sample\LinqtoSql\Default.aspx.cs:line 8
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
}