ExecuteScalar从'System.String'到'System.Guid'的无效转换

时间:2013-12-18 12:14:16

标签: asp.net sql vb.net

我正在尝试使用ExecuteScalar返回uniqueidentifier。但是,当我尝试运行它时,我收到此错误:

Invalid cast from 'System.String' to 'System.Guid'.
Exception Details: System.InvalidCastException: Invalid cast from 'System.String' to 'System.Guid'.

我的代码背后是这样的:

        Dim id As String = HttpContext.Current.Session("id")
    Dim file As String = HttpContext.Current.Session("file")
    connectionstring = ConfigurationManager.ConnectionStrings("ConnectionString1").ConnectionString.ToString
    Dim SQLConnection As New SqlConnection(connectionstring)
    SQLConnection.Open()

    Dim cmd As SqlCommand = New SqlCommand("GetFile", SQLConnection)

    Dim param1 As New SqlParameter()
    param1.ParameterName = "@id"
    param1.SqlDbType = SqlDbType.UniqueIdentifier
    param1.Direction = ParameterDirection.Input
    param1.Value = id

    Dim param2 As New SqlParameter()
    param2.ParameterName = "@file"
    param2.SqlDbType = SqlDbType.UniqueIdentifier
    param2.Direction = ParameterDirection.Input
    param2.Value = file

    cmd.CommandType = CommandType.StoredProcedure
    cmd.CommandText = "GetFile"
    cmd.Parameters.Add(param1)
    cmd.Parameters.Add(param2)

    cmd.ExecuteScalar()

    If cmd.ExecuteScalar.ToString = Nothing Then
        HttpContext.Current.Response.Redirect("Login.aspx")
    Else
        HttpContext.Current.Session("fileguid") = cmd.ExecuteScalar
    End If

存储过程定义了以下两个参数:

    @id uniqueidentifier, 
@file uniqueidentifier

只是使用这两个参数来验证它们是否存在于同一记录中。 select语句是:

SELECT [file] FROM [dbo].[files] WHERE [cid] = @id AND [file] = @file

希望你能提供帮助。

1 个答案:

答案 0 :(得分:0)

您的ID和文件是字符串,将它们转换为GUID

var idGuid = new System.Guid(id);
var fileGuid = new System.Guid(file);

并将它们传递给存储过程

param1.Value = idGuid;
...
param2.Value = fileGuid;