I have an object of type Employee which has a Guid property. I know if I want to set to null I must to define my type property as nullable Nullable<Guid>
prop or Guid? prop.
But in my case I'm not able to change the type of the prop, so it will remains as Guid type and my colleague and I we don't want to use the Guid.Empty.
Is there a way to set my property as null or string.empty in order to restablish the field in the database as null.
I have a mechanism to transform from string.empty to null but I will change many things if the would change to accept a empty guid to null.
Any help please!
you can make guid variable to accept null first using ? operator then you use Guid.Empty or typecast it to null using (Guid?)null;
eg:
Guid? id = Guid.Empty;
or
Guid? id = (Guid?)null;
I think this is the correct way:
Guid filed = Guid.Empty;
Since "Guid" is not nullable, use "Guid.Empty" as default value.
extrac Guid values from database functions:
#region GUID
public static Guid GGuid(SqlDataReader reader, string field)
{
try
{
return reader[field] == DBNull.Value ? Guid.Empty : (Guid)reader[field];
}
catch { return Guid.Empty; }
}
public static Guid GGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
return reader[ordinal] == DBNull.Value ? Guid.Empty : (Guid)reader[ordinal];
}
catch { return Guid.Empty; }
}
public static Guid? NGuid(SqlDataReader reader, string field)
{
try
{
if (reader[field] == DBNull.Value) return (Guid?)null; else return (Guid)reader[field];
}
catch { return (Guid?)null; }
}
public static Guid? NGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
if (reader[ordinal] == DBNull.Value) return (Guid?)null; else return (Guid)reader[ordinal];
}
catch { return (Guid?)null; }
}
#endregion
Guid? myGuidVar = (Guid?)null;
It could be. Unnecessary casting not required.
Guid? myGuidVar = null;
Choose your poison - if you can't change the type of the property to be nullable then you're going to have to use a "magic" value to represent NULL. Guid.Empty
seems as good as any unless you have some specific reason for not wanting to use it. A second choice would be Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff")
but that's a lot uglier IMHO.
You can use typeof(Guid), "00000000-0000-0000-0000-000000000000"
for DefaultValue of the property.
Source: Stackoverflow.com