Sandip
Sandip

Reputation: 481

how to store null to guid column in database

I am new in ASP.NET and C# and use mysql as well as postgresql.

I am trying to store Null value to GUId column in database.but it gives error while saving data because it default take guid.empty value to database.

can anyone please tell how can I store null value from C# code to Database ?

Thanks

Upvotes: 0

Views: 2104

Answers (2)

Baron von Connor
Baron von Connor

Reputation: 48

Well pretty sure you've basically got two options.

  1. Change the Database column to allow nulls.
  2. Use Guid.Empty and use some logic in your other table population to ensure the column you're referencing elsewhere does not use an empty guid.

This might be bad form(?) but also remember the sheer number of possible Guids, if you're worried about a Guid randomly BEING empty the likelihood of this ever happening unless you're dealing with a staggering amount of records is IMMENSELY unlikely. Provided that is you are using Guid.NewGuid() to generate your Guid of course.

Upvotes: 1

Az Za
Az Za

Reputation: 394

It is likely that you are using the classic Guid structure . If your code looks like this:

public class Dog
{
    public Guid Token { get; set;}
}

then you are using the classic Guid structure. Since 'Guid' is a struct type, the reference 'Token' will always have a value, which by default is all zeros. What you want (if you wish to make the Guid truly nullable) is to use the nullable type modifier on the Guid struct. It looks like the following:

public class Dog
{
     public Guid? Token { get; set;}
}

Now, if you don't assign a value to 'Token', it will be null.

* Be aware this may introduce subtle changes and hard to track NullExceptions.*

Upvotes: 1

Related Questions