Cast ExecuteScalar result to a GUID with out using a string?
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 scal开发者_如何学运维ar value.
Update: I also need to handle DBNull Values
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.
If the object being returned from the command is a UniqueIdenitifier, then yes.
Guid myResult = cmd.ExecuteScalar() as Guid? ?? Guid.Empty;
精彩评论