Cast ExecuteScalar results in GUID using string?

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

The reason for this is performance rather than creating thousands of unnecessary string objects in memory.

It is possible to use a reader and the GetGUID method, but I do not see any links to how to achieve this using a scalar value.

Update: I also need to handle DBNull values

+4
source share
3 answers

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

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

EDIT: Now that we know you need to process zeros .... :-)

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

Consider some form of helper function or extension method that checks 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 data type other than UniqueIdentifier.

+7
source

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

-1
source
  Guid myResult = cmd.ExecuteScalar() as Guid? ?? Guid.Empty; 
-1
source

Source: https://habr.com/ru/post/1334946/


All Articles