Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable GUID

In my database, in one of the table I have a GUID column with allow nulls. I have a method with a Guid? parameter that inserts a new data row in the table. However when I say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'."

like image 809
kjv Avatar asked Oct 17 '08 08:10

kjv


People also ask

What is nullable GUID?

C# Language Guid Declaring a nullable GUID myGuidVar = null; This is particularly useful when retrieving data from the data base when there is a possibility that value from a table is NULL.

Can system GUID be null?

A Guid is a struct , those can't be null.

What is the default value of GUID in C#?

default Guid is {00000000-0000-0000-0000-000000000000} . It's basically binary zeroes.

Is Empty GUID valid?

Empty is "{00000000-0000-0000-0000-000000000000}" which located the representation range of a guid, but we just marked is as Empty, so it is safe to use (someGuid ==Guid. Empty).


2 Answers

The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g.

myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value 

It's painful extra work that ADO.NET should handle, but it doesn't seem to do so reliably (even in 3.5 SP1). This at least works correctly.

We've also seen issues with passing nullable value types to SqlParameters where the generated SQL includes the keyword DEFAULT instead of NULL for the value so I'd recommend the same approach when building parameters.

like image 78
Greg Beech Avatar answered Oct 07 '22 15:10

Greg Beech


OK; how is myGuidColumn defined, and how is myGuid defined?

If myGuid is Guid? and myGuidColumn is Guid, then the error is correct: you will need to use myGuid.Value, or (Guid)myGuid to get the value (which will throw if it is null), or perhaps myGuid.GetValueOrDefault() to return the zero guid if null.

If myGuid is Guid and myGuidColumn is Guid?, then it should work.

If myGuidColumn is object, you probably need DBNull.Value instead of the regular null.

Of course, if the column is truly nullable, you might simply want to ensure that it is Guid? in the C# code ;-p

like image 41
Marc Gravell Avatar answered Oct 07 '22 15:10

Marc Gravell