Linq to sql Linq到sql连接(存储过程)引发强制转换异常

Linq to sql Linq到sql连接(存储过程)引发强制转换异常,linq-to-sql,asp.net-4.0,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

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

它似乎无法将作为类别返回的数据转换为Int32。是否有可能返回空值?或者,对于在数据列中声明的Bigint数据类型,超出Int32的最小/最大值的值使用Int64。。。它对我有用…

存储过程是什么样子的?我猜您的代码正在寻找一个类别对象,但您的进程正在返回一个结果集,您需要将该结果集强制转换为一个类别。@Brian我存储的进程包含select query。。。。我如何解决这个问题…您可以对实体执行linq查询而不是调用存储过程吗?为什么不调用SP。。。有什么问题吗?因为你在处理两件不同的事情。您需要转到ado.net和存储过程或linq。您可以尝试将return转换为Category对象,但更可能的情况是,您必须遍历return并分配属性。是否返回数据集?运行存储的过程,查看返回的数据,确认无数据为null,且所有数据都在int.min和int.max范围内
  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: 
    }