Nullable GUID

后端 未结 10 2206
北荒
北荒 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 05:00

    If you are into extension methods...

    /// 
    /// Returns nullable Guid (Guid?) value if not null or Guid.Empty, otherwise returns DBNull.Value
    /// 
    public static object GetValueOrDBNull(this Guid? aGuid)
    {
      return (!aGuid.IsNullOrEmpty()) ? (object)aGuid : DBNull.Value;
    }
    
    /// 
    /// Determines if a nullable Guid (Guid?) is null or Guid.Empty
    /// 
    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.

提交回复
热议问题