Tuesday, October 14, 2008

Store a type String value into type Guid

Sometimes, it is a good practice to use uniqueidentifier data type as your primary key in your database so that it eases your job when you are trying to merge your data from multiple data sources/locations.

however, the value is displayed as string in your application and when you want retrieve a data using the uniqueidentifier/Guid, the application will throw an exception because it does not allow you to input string for the type of Guid. Most of the function will look like:

public MembershipUser GetUserById(object key);

so if you call below statement will cause you an error:

MembershipUser user = GetUserById("23c46d23-8459-46fe-9e19-2da6800ef654"); //wrong

In fact, you need to use this:

MembershipUser user = GetUserById(new Guid("23c46d23-8459-46fe-9e19-2da6800ef654")); //Correct

No comments: