处理 SQL Server 和强类型数据集中的 null GUID
我在 SQL Server 中有一个表:
Categories
--------------
CategoryID (uniqueidentifier)
ParentCategoryID (uniqueidentifier) allow nulls
ParentCategoryID 旨在保存 CategoryID 中的值以指示哪个类别是父类别。 如果它没有父级(即它是顶级类别),则 ParentCategoryID 应为 null。
我正在使用强类型数据集(表适配器),并且对于 ParentCategoryID 的属性,它不允许它为空。 我尝试更改类型化数据集中字段的属性,但它说尝试将 guid 设置为“空”或“无”是无效的。 唯一的选择是抛出 null 异常。 这会导致错误:
表“Categories”中列“ParentCategoryID”的值为 DBNull。
是这样吗?或者在使用类型化数据集时有没有办法处理 null GUID/uniqueidentifiers?
I have a table in SQL server:
Categories
--------------
CategoryID (uniqueidentifier)
ParentCategoryID (uniqueidentifier) allow nulls
ParentCategoryID is meant to hold a value in CategoryID to indicate which category is the parent. If it has no parent (i.e. it's a top category) then ParentCategoryID should be null.
I'm using strongly typed datasets (table adapters) and for the properties for ParentCategoryID it does not allow it to be null. I've tried to change the properties for the field in the typed dataset but it says trying to make a guid "empty" or "nothing" is not valid. The only option is to throw an exception on null. This results in an error:
The value for column 'ParentCategoryID ' in table 'Categories' is DBNull.
Is this how it is, or is there a way to handle null GUID/uniqueidentifiers when using typed datasets?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您已使用 Visual Studio 生成器并且已正确检测到表的所有内容,则可为 null 的列将在强类型 DataRow 上生成以下内容:
假设您的强类型表名为“My”(生成
MyDataTable
和MyDataRow
),您的DataSet
名为MyDataSetType
,实例名为myDataSet
:您还可以查看实现
SetParentCategoryID
以查看用于执行“nulling”的内容。此外,要检测“空 GUID”:
现在您有三种不同类型的值来表示状态:
Guid.Empty
)guid(???)当我第一次遇到这个问题时,我认为应该使用
Guid.Empty
来表示数据库中的空条目,但这需要对 guid 类型进行自定义处理。 使用包装器函数,强类型数据集可以基于结构样式类型对任意数量的可为空列提供一致的处理。If you have used the Visual Studio generators and everything is detected properly for your table, then a nullable column will generate the following on your strongly typed DataRow:
Given that your strongly typed table is named "My" (Generates
MyDataTable
andMyDataRow
), yourDataSet
is namedMyDataSetType
, and the instance is namedmyDataSet
:You can also look at the implementation of
SetParentCategoryID
to see what is used to do a "nulling".Further, to detect a "null guid":
So now you have three different types of values to represent state:
Guid.Empty
) guid (???)When i first ran into this problem, I thought
Guid.Empty
should have been used to represent a null entry in the database, but that would have required custom handling of the guid type. Using the wrapper functions, the strongly typed dataset can provide consistent handling of any number of nullable columns based on struct-style types.