开发者

SQL Server unique-identifier equivalent in C#

What datatype should I use开发者_运维问答 in C# to work with the SQL Server uniqueidentifier.

Do I need any conversions etc ?


System.Guid

No conversions needed.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜