C# 可为空的 GUID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/211436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:16:18  来源:igfitidea点击:

Nullable GUID

c#.netsql-serverguidnullable

提问by kjv

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 say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'."

在我的数据库中,在其中一个表中,我有一个允许为空的 GUID 列。我有一个带有 Guid 的方法?在表中插入新数据行的参数。但是,当我说 myNewRow.myGuidColumn = myGuid 时,我收到以下错误:“无法隐式转换类型 'System.Guid?' 到'System.Guid'。”

采纳答案by Greg Beech

The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g.

ADO.NET API 在处理可空值类型时存在一些问题(即它无法正常工作)。我们一直没有解决它的问题,因此得出的结论是最好将值手动设置为 null,例如

myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value

It's painful extra work that ADO.NET should handle, but it doesn't seem to do so reliably (even in 3.5 SP1). This at least works correctly.

ADO.NET 应该处理的额外工作很痛苦,但它似乎并不可靠(即使在 3.5 SP1 中)。这至少可以正常工作。

We've also seen issues with passing nullable value types to SqlParameters where the generated SQL includes the keyword DEFAULTinstead of NULLfor the value so I'd recommend the same approach when building parameters.

我们还看到了将可为空值类型传递给 SqlParameters 的问题,其中生成的 SQL 包含关键字DEFAULT而不是NULL值,因此我建议在构建参数时使用相同的方法。

回答by Marc Gravell

OK; how is myGuidColumn defined, and how is myGuid defined?

好的; myGuidColumn 是如何定义的,myGuid 是如何定义的?

If myGuid is Guid?and myGuidColumn is Guid, then the error is correct: you will need to use myGuid.Value, or (Guid)myGuidto get the value (which will throw if it is null), or perhaps myGuid.GetValueOrDefault()to return the zero guid if null.

如果 myGuid 是Guid?并且 myGuidColumn 是Guid,那么错误是正确的:您将需要使用myGuid.Value, 或(Guid)myGuid获取值(如果它为空,则会抛出),或者如果为空,则可能myGuid.GetValueOrDefault()返回零 guid。

If myGuid is Guidand myGuidColumn is Guid?, then it should work.

如果 myGuid 是Guid并且 myGuidColumn 是Guid?,那么它应该可以工作。

If myGuidColumn is object, you probably need DBNull.Valueinstead of the regular null.

如果 myGuidColumn 是object,则您可能需要DBNull.Value而不是常规的空值。

Of course, if the column is truly nullable, you might simply want to ensure that it is Guid?in the C# code ;-p

当然,如果该列确实可以为空,您可能只想确保它Guid?在 C# 代码中;-p

回答by TcKs

You can use a helper method:

您可以使用辅助方法:

public static class Ado {
    public static void SetParameterValue<T>( IDataParameter parameter, T? value ) where T : struct {
        if ( null == value ) { parameter.Value = DBNull.Value; }
        else { parameter.Value = value.Value; }
    }
    public static void SetParameterValue( IDataParameter parameter, string value ) {
        if ( null == value ) { parameter.Value = DBNull.Value; }
        else { parameter.Value = value; }
    }
}

回答by TcKs

or:

或者:

    internal static T CastTo<T>(object value)
    {
        return value != DBNull.Value ? (T)value : default(T);
    }

回答by Isak Savo

If you want to avoid working with nullable GUIDs in your c# code (personally, I often find it cumbersome to work with nullable types) you could somewhere early assign Guid.Emptyto the .NET data which is null in the db. That way, you don't have to bother with all the .HasValue stuff and just check if myGuid != Guid.Emptyinstead.

如果您想避免在您的 c# 代码中使用可为空的 GUID(就我个人而言,我经常发现使用可为空的类型很麻烦),您可以尽早将Guid.Empty分配给 .NET 数据,该数据在 db 中为空。这样,您就不必费心处理所有 .HasValue 内容,而只需检查是否存在myGuid != Guid.Empty

回答by cheeves

same as Greg Beech's answer

与 Greg Beech 的回答相同

myNewRow.myGuidColumn = (object)myGuid ?? DBNull.Value

回答by Imran

Try System.Guid.Empty where you want it to be null

尝试 System.Guid.Empty 您希望它为空的地方

回答by Justin

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();

那你可以说: 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.

注意:这将在 时插入空值myGuid == Guid.Empty,如果您想在您的列中允许空的 Guids,您可以轻松地调整该方法。

回答by Chtiwi Malek

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

你必须投射null到 a nullable Guid,这对我来说是如何工作的:

myRecord.myGuidCol = (myGuid == null) ? (Guid?)null : myGuid.Value

回答by maurox

Guid? _field = null;
if (myValue!="")//test if myValue has value
{
_field = Guid.Parse(myValue)
}