Cast ExecuteScalar result to a GUID with out using a string?
Asked Answered
H

3

5

How can I cast the result of an ExecuteScalar command to a GUID structure without first using .ToString() to pass to the constructor of the GUID?

The reason for doing this is performance and not creating thousands of unnecessary string objects in memory.

It is possible using a reader and the GetGUID Method but I can not see any references to how to achieve the same when using a scalar value.

Update: I also need to handle DBNull Values

Harewood answered 10/1, 2011 at 16:10 Comment(0)
G
10

Assuming that your sql statement cannot return DBNull.Value, then yes you can:

Guid myResult = (Guid) cmd.ExecuteScalar();

EDIT: Now that we know you need to handle nulls.... :-)

I can think of two ways to handle nulls - use a nullable Guid and set it to null, or use a regular Guid and have it set to Guid.Empty if your SQL statement returns null.

Consider some form of helper function or extension method which checks for DBNull.Value.

    static Guid? GetGuidFromDb(object dbValue)
    {
        if (dbValue == null || DBNull.Value.Equals(dbValue))
        {
            return null;
        }
        else
        {
            return (Guid) dbValue;
        }
    }

or

    static Guid GetGuidFromDb(object dbValue)
    {
        if (dbValue == null || DBNull.Value.Equals(dbValue))
        {
            return Guid.Empty;
        }
        else
        {
            return (Guid) dbValue;
        }

Then call

Guid? myResult = GetGuidFromDb(cmd.ExecuteScalar());

Note - this will choke if your SQL command returns a datatype other than UniqueIdentifier.

Gotha answered 10/1, 2011 at 16:33 Comment(1)
Thanks - I had initially forgot about the DBNulls and that is why I was struggling as they do not evaluate to normal nulls.Harewood
B
-1

If the object being returned from the command is a UniqueIdenitifier, then yes.

Berneicebernelle answered 10/1, 2011 at 16:31 Comment(0)
B
-1
    Guid myResult = cmd.ExecuteScalar() as Guid? ?? Guid.Empty;
Bohner answered 17/2, 2016 at 12:5 Comment(2)
This does not handle DBNull as requested. DBNull is not the same as null.Agan
It is also generally better to explain how your answer works, so that the asker and others in the community may learn from it. Maybe have a look at stackoverflow.com/help/how-to-answerAgan

© 2022 - 2024 — McMap. All rights reserved.