我不明白为什么服务器遇到错误并提请注意以下代码中的 foreach
循环
using Microsoft.CSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using AllyPortal.Models;
using System.Web.Script.Serialization;
namespace AllyPortal.Controllers
{
public class AssetBundleController : Controller
{
[HttpGet]
public ActionResult Index(string bguid)
{
// bguid: bundle guid, the guid corresponding to one or more assets in the table
PortalData PD = new PortalData();
ViewBag.inputtedGuid = bguid;
ViewBag.checkedAssetLinks = new List<string> ();
foreach (AssetLink thislink in PD.links)
{
if (thislink.linkguid.Equals(bguid, StringComparison.Ordinal))
{
AssetFile thisAssetFile = PD.files.FirstOrDefault(f => f.fileid == thislink.fileid);
ViewBag.links.Add("../../Assets/" + PD.getFullFileName(thisAssetFile));
}
}
return View();
}
}
}
作为引用,有问题的模型是
[Table( Name = "links")]
public class AssetLink
{
public AssetLink()
{
}
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int linkid { get; set; }
[Column]
public string linkguid { get; set; }
[Column]
public int fileid { get; set; }
}
里面
public class PortalData : DataContext
{
...
}
还有一个类
[Table( Name = "files" )]
public class AssetFile
{
public AssetFile()
{
}
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int fileid { get; set; }
[Column]
public int orgid { get; set; }
[Column]
public int catid { get; set; }
[Column]
public string filename { get; set; }
}
我曾经用它来迭代
foreach (AssetFile f in PD.files)
{
....
}
在另一个 Controller 中,那么这个可能导致错误的 Controller 有何不同?让我知道是否需要发布更多代码以为您提供引用。
蓝屏死机:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Specified cast is not valid.
Source Error:
Line 26: ViewBag.assetLinks = new List (); Line 27: Line 28: foreach (AssetLink thislink in PD.links) Line 29: { Line 30:
Source File: c:\Users\me\Documents\Visual Studio 2013\Projects\someproj\someproj\Controllers\AssetBundleController.cs Line: 28
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Int32() +5317537
System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i) +62
最佳答案
查看堆栈跟踪,错误发生在这里:
System.Data.SqlClient.SqlBuffer.get_Int32() +5317537
尝试枚举 PD.links
时。这似乎表明您从其中一个 int
属性的源中获得了不同的类型。检查links
表中linkid
和fileid
的数据类型,确保它们都是整数类型。
关于c# - 在这种情况下,为什么 "Specified cast is not valid."是没有意义的。或者是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328247/