Тип сходства System.Data.SQLite int в строковом столбце - PullRequest
1 голос
/ 20 октября 2011

Из того, что я читал о SQLite, он имеет функцию, называемую Type Affinity, которая означает, что типы данных не строго соблюдаются ( Подробнее здесь ).

Я читаю из базы данных, созданной в другом приложении, используя объекты POCO с EF4.1, проблема возникает, когда в предположительно строковом поле есть целое число . Я мог бы понять, что возникает исключение, если в поле int есть нечисловая строка ... но почему это испортило мое приложение?

Это пример моего тестового кода, я удалил все остальное, пока у меня не осталось минимума кода, который делает это всплывающим.

Public Class TVSerie
    Public Property Id As Integer
    Public Property PrettyName As String
End Class

Public Class TVSeriesDb
    Inherits DbContext
    Public Property TVSeries As DbSet(Of TVSerie)
End Class

Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Function Index() As ActionResult
        Dim db As New TVSeriesDb
        Dim sb As New StringBuilder
        Dim series = db.TVSeries.Where(Function(c) c.PrettyName.Length > 0)
        For Each s In series
            sb.Append(s.Id & "-" & s.PrettyName & "<br/>")
        Next
        Return Content(sb.ToString)
    End Function
End Class

Ошибка появляется в столбце «PrettyName» с TVSeries 24:

[InvalidCastException: Specified cast is not valid.]
System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ) +492
System.Data.SQLite.SQLiteDataReader.GetString(Int32 i) +131
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target,   Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner) +0
   System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner) +72
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +251
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +28
   System.Data.Common.Internal.Materialization.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal) +342
   System.Data.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling(Int32 ordinal, String propertyName, String typeName) +79
   lambda_method(Closure , Shaper ) +167
   System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly(Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) +218
   lambda_method(Closure , Shaper ) +291
   System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) +170
   System.Data.Common.Internal.Materialization.SimpleEnumerator.MoveNext() +84
   Test.Controllers.HomeController.Index() in C:\Projects\PlayListShuffler\Test\Controllers\HomeController.vb:14
   lambda_method(Closure , ControllerBase , Object[] ) +96
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8920029
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

1 Ответ

0 голосов
/ 23 ноября 2012

Несмотря на то, что sqlite не является строго типизированным (что очень хорошо работает с динамически типизированным языком, таким как Python), в оболочке применяется строго типизированная природа .NET. Таким образом, тип столбца, обнаруженного при чтении таблицы, является типом, который требуется для Reader.Getxxx (n).

...