2012-04-24 119 views
0

我需要通过执行存储过程通过linq操作来访问数据。 请看下面我的代码。告诉我我哪里出错了。Linq to sql连接(存储过程)抛出抛出异常

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: 
    } 
+0

什么是存储过程是什么样子?我的猜测是你的代码正在寻找一个类别对象,但你的proc正在返回一个结果集,你需要将该结果集转换为一个类别。 – Brian 2012-04-24 13:06:48

+0

@布赖恩我的存储过程包含选择查询....我如何解决此问题... – 2012-04-24 13:18:24

+0

而不是调用存储过程你可以做一个linq查询对实体? – Brian 2012-04-24 13:38:09

回答

0

使用的Int64对于以数据列声明BIGINT数据类型...它为我的作品...

1

这样看来它不能转换回来作为分类成一个Int32数据。是否有可能返回空值?或者Int32的Min/Max以外的值?

+0

所以我需要做的...... – 2012-04-25 06:41:03

+0

运行存储过程,看看有什么数据回来,验证没有为空,所有都在int.min和int.max范围内 – taylonr 2012-04-25 12:21:07