【问题标题】:SQLProvider Unable to cast object of type 'System.Guid' to type 'System.String'SQLProvider 无法将类型为 \'System.Guid\' 的对象转换为类型 \'System.String\'
【发布时间】:2022-11-04 04:42:31
【问题描述】:

我正在使用 SQLProvider 在 F# 项目中进行查询。在我的数据库中,我有一列存储 GUID - 'Id' char(36) NOT NULL。当进行查询时,我得到一个错误:

Unhandled exception. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.String'.

我正在使用 MySqlConnector 作为驱动程序。

这是表在 DB 中的外观

CREATE TABLE `Comics` (
  `Id` char(36) NOT NULL,
  `Price` double DEFAULT NULL,
  `Title` char(255) DEFAULT NULL,
  `Image` char(255) DEFAULT NULL,
  `Description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

这是基于 DB 生成的类型

这是一个查询

let ctx = sql.GetDataContext()
let ComicsTable = ctx.ComicsShop.Comics;

let getById (id: string) =
  query {
      for c in ComicsTable do
      where (c.Id = id)
      select c.Id
  } |> Seq.head

和用法

let result =
    getById "0e49d94e-76c4-44be-b2ea-38382b297c78"

Console.WriteLine(result)

谢谢你的帮助。

【问题讨论】:

  • 错误是什么?
  • 当您将光标悬停在 getById 的 id 参数上时,您会看到什么类型?
  • @FyodorSoikin 完全错误:Unhandled exception. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.String'.
  • @jimfoye @987654329 @c.id字符串
  • 在发布之前,请说明所有参数(id),尤其是在类型的问题中。如果不这样做,您就会让用户在开始解决您的问题之前解决一个难题(id 的推断类型应该是什么)。

标签: f# mysql-connector


【解决方案1】:

经过一段时间的调查,问题出在DB上。 我的Id 字段的类型为char(36),它被转换为字符串。但由于该列包含 GUID,SQLProvider 将假设该字段为 Guid 进行查询,并且会在运行时引发错误。 解决方案很简单 Id 包含 Guid 的列应键入为 varchar(36) 然后所有类型都将正确转换。

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2012-09-07
    • 1970-01-01
    • 2014-03-14
    • 2017-11-24
    • 1970-01-01
    • 2021-04-26
    • 2017-03-04
    相关资源
    最近更新 更多