【问题标题】:EF executestorequery throwing exception about - Conversion failed when converting the varchar value '30267-366492' to data type intEF executestorequery 引发异常 - 将 varchar 值“30267-366492”转换为数据类型 int 时转换失败
【发布时间】:2016-12-07 18:09:03
【问题描述】:

我正在尝试使用 EF executestorequery 执行 sql 查询。

执行查询的存储库方法如下。它接受一个元组列表 (studentid, sectionid) 并构造一个作为查询输入参数的 studentid-sectionid 值字符串。

public static List<EF.TraditionalGradingEntity> GetTraditionalGrading(List<Tuple<int, int>> studentSectionIds)
{
    List<string> tempList = new List<string>();
    foreach (Tuple<int, int> studentSectionId in studentSectionIds)
    {
        tempList.Add(studentSectionId.Item1.ToString() + "-" + studentSectionId.Item2.ToString());
    }
    string stuSecIds = string.Join(",", tempList.ToArray());
    string strTdlGradingQuery = string.Format(
        @"
        select 
            tbgTraj.studentPersonID,
            tbgTraj.sectionID,
            tbgTraj.studentPersonID_SectionID,
            tbgTraj.score,
            tbgTraj.sel,
            tbgTraj.growth,
            tbgTraj.warning,
            tbgTraj.taskID,
            tbgTraj.gradingTask,
            tbgTraj.taskScore,
            tbgScore.groupName,
            tbgScore.activityName,
            tbgScore.score activityScore
        from
            [shs].[DataCollector_TBG_Grade_Trajectory] tbgTraj
            inner join [shs].[DataCollector_TBG_Scores] tbgScore 
                on tbgTraj.taskID = tbgScore.taskID 
                and tbgTraj.studentPersonID = tbgScore.studentPersonID 
                and tbgTraj.sectionID = tbgScore.sectionID
        where
            tbgTraj.studentPersonID_SectionID in ({0})
        ", stuSecIds);

    using (EF.AESDBContext aesDBContext = new EF.AESDBContext())
    {
        return aesDBContext.ObjectContext.ExecuteStoreQuery<EF.TraditionalGradingEntity>(strTdlGradingQuery, "TraditionalGradings", MergeOption.OverwriteChanges, null).ToList();
    }
}

我的实体定义如下

public class TraditionalGradingEntity
{
    public int StudentPersonId { get; set; }
    public int SectionId { get; set; }
    public string StudentPersonID_SectionID { get; set; }
    public string Score { get; set; }
    public string Sel { get; set; }
    public string Growth { get; set; }
    public string Warning { get; set; }
    public int TaskId { get; set; }
    public string GradingTask { get; set; }
    public string TaskScore { get; set; }
    public string GroupName { get; set; }
    public string ActivityName { get; set; }
    public string ActivityScore { get; set; }
}

现在,无论输入参数值如何,执行总是失败并出现以下异常:

System.Data.EntityCommandExecutionException was unhandled by user code
  HResult=-2146232004
  Message=An error occurred while reading from the store provider's data reader. See the inner exception for details.
  Source=System.Data.Entity
  StackTrace:
       at System.Data.Common.Internal.Materialization.Shaper`1.StoreRead()
       at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at D125Portal.DA.EbrRepository.GetTraditionalGrading(List`1 studentSectionIds) in C:\Users\rgopinathan\Source\Workspaces\Workspace_D125New\EBRLevel\D125Portal\D125Portal.DataAccess\EbrRepository.cs:line 218
       at D125Portal.BL.EBR.ReportS.Init() in C:\Users\rgopinathan\Source\Workspaces\Workspace_D125New\EBRLevel\D125Portal\D125Portal.BL\EBR\ReportS.cs:line 73
       at D125Portal.BL.EBR.ReportManager.GetReport(ReportRequestS req) in C:\Users\rgopinathan\Source\Workspaces\Workspace_D125New\EBRLevel\D125Portal\D125Portal.BL\EBR\Report.cs:line 79
       at D125Portal.WWW.Areas.EBR.Coordinator.GetStudentReport(List`1 students) in C:\Users\rgopinathan\Source\Workspaces\Workspace_D125New\EBRLevel\D125Portal\D125Portal\Areas\EBR\Coordinator.cs:line 106
       at D125Portal.WWW.Areas.EBR.Controllers.EBRHomeController.Report() in C:\Users\rgopinathan\Source\Workspaces\Workspace_D125New\EBRLevel\D125Portal\D125Portal\Areas\EBR\Controllers\EBRHomeController.cs:line 164
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
  InnerException: System.Data.SqlClient.SqlException
       HResult=-2146232060
       Message=Conversion failed when converting the varchar value '30267-366492' to data type int.
       Source=.Net SqlClient Data Provider
       ErrorCode=-2146232060
       Class=16
       LineNumber=2
       Number=245
       Procedure=""
       Server=ovdcovyjrr.database.windows.net
       State=1
       StackTrace:
            at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
            at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
            at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
            at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
            at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
            at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
            at System.Data.SqlClient.SqlDataReader.Read()
            at System.Data.Common.Internal.Materialization.Shaper`1.StoreRead()
       InnerException: 

注意:异常消息中的值“30267-366492”始终相同,与输入参数值和输出数据无关(即使输出不包含此值)。我能够成功地单独运行查询,但不能通过程序运行。非常感谢任何见解或帮助。

【问题讨论】:

  • 您忘记将单引号括在您连接在一起的值周围并格式化为您的查询。
  • 好的,谢谢。这有帮助。因为异常显示了一个特定的值('30267-366492'),所以我很分心,不知道它是从哪里挑选出来的,而且还反复检查实体类映射以确保正确分配了数据类型。跨度>

标签: c# sql asp.net-mvc entity-framework


【解决方案1】:
tempList.Add(studentSectionId.Item1.ToString() + "-" + studentSectionId.Item2.ToString())
...
string stuSecIds = string.Join(",", tempList.ToArray());

在这里,您可能正在以类似于0-3, 1-4, 2-5 的方式连接整数。所以总的来说,你的 where 子句是:where tbgTraj.studentPersonID_SectionID in (-3, -3, -3)。注意这些是integers,因为- 被解释为减法。在您的tbgTraj.studentPersonID_SectionID 中,您获得了'30267-366492' 的值,它不会转换为int。 SQL 服务器尝试将其隐式转换为 int,因为在比较 string = int 时,int 优先 (see here)。

所以您的解决方案是在您的 id 周围使用引号:

"'" + studentSectionId.Item1.ToString() + "-" + + studentSectionId.Item2.ToString() "'" ...

另外,请注意bobby tables。你应该参数化你的查询以避免sql注入!

【讨论】:

  • 谢谢。虽然没有发生减法(因为我有 ToString()),但在 id 对周围添加单引号有助于克服异常。
  • 减法发生在sql解释中。很高兴它有帮助
【解决方案2】:

确保在您的 id 对列表周围加上单引号,以便将 studentPersonID_SectionID 与一组字符串而不是一组整数进行比较(这些数字最终会在 SQL 中减去)。

tempList.Add(string.Format(
    "'{0}-{1}'", 
    studentSectionId.Item1,
    studentSectionId.Item2));

【讨论】:

  • 谢谢。虽然没有发生减法(因为我有 ToString()),但在 id 对周围添加单引号有助于克服异常。
  • 我所说的减法的意思是你在 SQL 查询中有类似 In (30267-366492) 的东西,它会导致类似 In (-336225) 的东西,因为 SQL 服务器会将 30267-366492 视为减法。
  • 啊,好的。得到你。感谢您的回复,感谢您的帮助。
猜你喜欢
  • 2011-12-01
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多