Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to SQL Server uniqueidentifier in asp.net

Is there any built-in method in asp.net to convert a string to a uniqueidentifier for SQL Server, just like .ToString().

I get an error: Conversion failed when converting from a character string to uniqueidentifier.

Or does anyone have an idea how to do solve this problem. Thanks.

like image 391
4b0 Avatar asked Dec 13 '22 08:12

4b0


2 Answers

There's a constructor for Guid which takes a string as a parameter.

Guid aGuid = new Guid(aString);

Make sure it's in the correct format:

A string that contains a GUID in one of the following formats ("d" represents a hexadecimal digit whose case is ignored):

32 contiguous digits: dddddddddddddddddddddddddddddddd

-or-

Groups of 8, 4, 4, 4, and 12 digits with hyphens between the groups. The entire GUID can optionally be enclosed in matching braces or parentheses: dddddddd-dddd-dddd-dddd-dddddddddddd -or- {dddddddd-dddd-dddd-dddd-dddddddddddd} -or- (dddddddd-dddd-dddd-dddd-dddddddddddd)

-or-

Groups of 8, 4, and 4 digits, and a subset of eight groups of 2 digits, with each group prefixed by "0x" or "0X", and separated by commas. The entire GUID, as well as the subset, is enclosed in matching braces: {0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}

Full documentation can be found here.

You can pass your RoleID guid in as a parameter:

Guid roleID = new Guid(roleIDAsString);
sqlCommand.Parameters.Add("@RoleID", SqlDbType.UniqueIdentifier).Value = roleID;
like image 120
Kasaku Avatar answered Feb 01 '23 23:02

Kasaku


Guid outGuid;
Guid.TryParse(stringInput, out outGuid);

Won't crash if the string is incorrectly formatted

like image 44
Crab Bucket Avatar answered Feb 01 '23 23:02

Crab Bucket