24

What datatype should I use in C# to work with the SQL Server uniqueidentifier.

Do I need any conversions etc ?

1

3 Answers 3

25

System.Guid

No conversions needed.

Sign up to request clarification or add additional context in comments.

1 Comment

Check this link if you have any other parameter data type mapping issues: msdn.microsoft.com/en-us/library/ms131092.aspx
15

System.Guid

When reading nullable Uniqueidentifier columns from your database, be sure to check if the value is null before attempting to assign to a Guid instance, as Guids are not nullable. For example:

... /// using recordset rs // generates exception if rs["my_guid"] is null Guid g = (Guid)rs["my_guid"]; // returns Guid.Empty {0000000-.....} if db value is null Guid g = (Guid)(rs["my_guid"] ?? Guid.Empty); 

etc.

3 Comments

Just use Guid? A.K.A. Nullable<Guid> and you can assign null.
That doesn't always work - ie, you'll have to wind up converting it to a non-nullable Guid at some point if you're passing to code that doesn't allow nullable Guids.
Any full source code sample using Guid? and considering DBNull != null?
2

If you are getting the value from a SQLDataReader, make sure to check it against DBNull before you try to use it. Sometimes the value can be interpreted as a string as well, so you need to type New Guid(rs["my_guid"]) to make sure you have a guid to use in your code.

2 Comments

login to comment on other answers
"login to comment on other answers" you see my username and icon, right? I'm logged in, but I don't have enough reputation to comment on other's posts...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.