Nullable GUID

后端 未结 10 2096
北荒
北荒 2020-12-15 04:36

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

相关标签:
10条回答
  • 2020-12-15 04:58

    same as Greg Beech's answer

    myNewRow.myGuidColumn = (object)myGuid ?? DBNull.Value
    
    0 讨论(0)
  • 2020-12-15 05:00

    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.

    0 讨论(0)
  • 2020-12-15 05:03

    You have to cast null to a nullable Guid, this how it worked for me :

    myRecord.myGuidCol = (myGuid == null) ? (Guid?)null : myGuid.Value
    
    0 讨论(0)
  • 2020-12-15 05:03

    or:

        internal static T CastTo<T>(object value)
        {
            return value != DBNull.Value ? (T)value : default(T);
        }
    
    0 讨论(0)
提交回复
热议问题