Reputation: 22323
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.
Upvotes: 4
Views: 20082
Reputation: 2192
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;
Upvotes: 9
Reputation: 11926
Check for the string value before using it
Guid g = new Guid(string) ;
Upvotes: 0
Reputation: 6277
Guid outGuid;
Guid.TryParse(stringInput, out outGuid);
Won't crash if the string is incorrectly formatted
Upvotes: 3
Reputation: 17701
string aspUserID = myObject.ProviderUserKey.ToString();
Guid userGuid = new Guid(aspUserID);
or
Guid yourGuid = new Guid(yourString);
Upvotes: 0