Linq to sql Connection(存储过程)抛出强制转换异常

时间:2012-04-24 13:02:15

标签: linq-to-sql asp.net-4.0

我需要通过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: 
    }

2 个答案:

答案 0 :(得分:1)

它似乎无法将作为Category返回的数据转换为Int32。是否可能会返回空值?或者是Int32的最小/最大值之外的值?

答案 1 :(得分:0)

Int64 用于在数据列中声明的 Bigint 数据类型...它对我有用...