Explain Codes LogoExplain Codes Logo

C# guid and SQL uniqueidentifier

sql
guid
sql-server
entity-framework
Anton ShumikhinbyAnton Shumikhin·Jan 24, 2025
TLDR

Let's get straight to the point. To pair C# Guid with SQL uniqueidentifier, you should use parameterized SQL commands.

using (var conn = new SqlConnection("YourConnectionString")) { // Ain't nobody got time for SQL Injection var query = "INSERT INTO Table (GuidColumn) VALUES (@guid)"; using (var cmd = new SqlCommand(query, conn)) { // Using Guid.NewGuid(), because we're unique ;) cmd.Parameters.AddWithValue("@guid", Guid.NewGuid()); conn.Open(); cmd.ExecuteNonQuery(); } }

There you have it - a succinct way of transmitting Guid data accurately from C# to SQL. By using AddWithValue, we're not just efficient but we also bypass the need for explicit SqlDbType declarations.

GUIDs: Practical Usage Across C# and SQL

Before we dive deeper into the nuances of GUID usage, it's crucial to understand the following best practices:

Play by the rules: Use correct data types

In C# we use System.Guid. SQL Server on the other hand, is a fan of uniqueidentifier.

public class Entity { // Just your everyday GUID public Guid Id { get; set; } }

And in SQL:

CREATE TABLE Entity ( // The one, the only, uniqueidentifier Id uniqueidentifier PRIMARY KEY );

The beauty here is Entity Framework, it's a real MVP, handling this conversion like a pro.

An Ounce of Prevention: Using parameterized queries

Prevention is better than cure, and likewise, SqlParameters over string concatenation. This gives us protection against Sylvia - the villain SQL injection. For this, we entrust our faith to SqlCommand.Parameters.AddWithValue.

command.Parameters.AddWithValue("@guid", entity.Id);

Using this command is like wearing your seatbelt. You might not need it every time, but when you do, you'll be glad you put it on!

Resource Management: Too much of anything is bad

Even too much cake can be harmful (although debatable). So is leaving SqlConnection and SqlCommand objects wandering around aimlessly. Let's round them up with using statements:

using (var connection = new SqlConnection(connectionString)) using (var command = new SqlCommand(query, connection)) { // The command is executed, no drama! }

Remember, cleaning up is not just for children; it helps keep our memory footprint teeny-tiny!

Consistency is key: Wrap it up with transactions

Speaking of wrapping, ever received a gift only to find out that the packaging was the most attractive part? That's how database operations can feel when they lack transactions.

using (var transaction = connection.BeginTransaction()) { try { command.Transaction = transaction; // The magic happens here transaction.Commit(); } catch (Exception) { transaction.Rollback(); // Oops! Better luck next time throw; } }

So, let's ensure that our operations are all gift and no fluff by calling transaction.Commit() on successful operations.

Check, Mate: Storing and retrieving GUIDs

In the world of SQL Server, a GUID cuts a striking 36-character figure.

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

And the best part - No need to gift wrap this one (single quotes) in parameterized queries, it's pretty as is!

Miss Manners: Use stored procedures

Let's not forget our P's & Q's while interacting with the database. When calling the cavalry (stored procedures), set the CommandType as such and send the GUID as our trusted envoy.

command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("@guid", entity.Id));

Notably, stored procedures deliver the consistency we love and the security we couldn't live without.

Visualise It

Take the lock-and-key analogy in the real world:

C# GUID: 🔑 (A unique key) SQL uniqueidentifier: 🔒 (A lock designed for that key)

The mechanism of pairing illustrates the harmony between the two:

🔑 -> 🔒 // Who said perfect match doesn't exist!
In databases:
🔑 = Unique identifier in C#
🔒 = uniqueidentifier column in SQL

A simple recipe for maintaining uniqueness and harmony across C# and SQL!