有时我会遇到以下恼人的错误,它不会一直发生似乎是随机的:
System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.Table`1.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
以下是似乎生成错误的代码:
public vwStaff GetUserDetails(string init) {
//Just to check if the initials are empty, if they are make an attempt to get them again
//Just put in place as an extra test, but not making any difference, will remove shortly
if (string.IsNullOrEmpty(init) || string.IsNullOrWhiteSpace(init)) {
init = F.GetUserInitials();
}
using (GlobalDataContext db = DataHelper.GetDataContext()) {
return db.vwStaffs.FirstOrDefault(w => w.StaffInitials == init);
}
}
vwStaff是一个标准的MsSQL2005视图,并没有什么花哨的
F.GetUserInitials,只是一个快速帮助方法:
public static string GetUserInitials() {
string userId = HttpContext.Current.User.Identity.Name.ToLower();
return userId.Remove(0, userId.LastIndexOf("\\", StringComparison.Ordinal) + 1);
}
我所能看到的一切都是一个字符串,所以不知道Int32在哪里进入它。我已根据代码映射检查了数据库,并且所有字段都匹配。
任何人都可以建议我接下来要看的地方。