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 s
same as Greg Beech's answer
myNewRow.myGuidColumn = (object)myGuid ?? DBNull.Value
If you are into extension methods...
/// <summary>
/// Returns nullable Guid (Guid?) value if not null or Guid.Empty, otherwise returns DBNull.Value
/// </summary>
public static object GetValueOrDBNull(this Guid? aGuid)
{
return (!aGuid.IsNullOrEmpty()) ? (object)aGuid : DBNull.Value;
}
/// <summary>
/// Determines if a nullable Guid (Guid?) is null or Guid.Empty
/// </summary>
public static bool IsNullOrEmpty(this Guid? aGuid)
{
return (!aGuid.HasValue || aGuid.Value == Guid.Empty);
}
Then you could say:
myNewRow.myGuidColumn = myGuid.GetValueOrDBNull();
NOTE: This will insert null when myGuid == Guid.Empty
, you could easily tweak the method if you want to allow empty Guids in your column.
You have to cast null
to a nullable Guid
, this how it worked for me :
myRecord.myGuidCol = (myGuid == null) ? (Guid?)null : myGuid.Value
or:
internal static T CastTo<T>(object value)
{
return value != DBNull.Value ? (T)value : default(T);
}