更新、外键约束和空值
我正在用 C# 生成数据模板。 在这个精彩网站上的好心人的帮助下,我几乎解决了所有问题。 这应该是最后一个问题。 因为这是我正在处理的模板,所以我想要表中的每个字段,包括空值。 我得到了如何通过添加 (object)this.field 来更新空值的帮助? DBNull.Value 但我有一个外键字段,即使当我查看数据库时它显示为 null,当我提取记录时该值变为 0。当我尝试更新此字段时它说我违反了外键限制。 我该如何解决这个问题? 我认为 null 解决方案可以工作,但它不显示为 null,它显示为 0。
谢谢
I am generating a data template in C#. With the help of the good people on this wonderful site, I've managed to take care of almost every issue. This should be the last problem. Because it's a template I'm working on, I want every field in the table, including nulls. I was helped on how to update nulls by adding (object)this.field ?? DBNull.Value but I have a field that's a foreign key and even though when I look in the database it says null, when I pull the records the value becomes 0. When I try to update this field it says that I am violating foreign key constraints. How can I work around this problem? I thought the null solution would work but it doesn't show as null, it shows as 0.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
0 是该列可能的有效值吗? 如果没有,则在遇到时将其类型转换为 null。 如果它有效,您仍然可以通过将其包装在首先检查外部行是否存在的条件中来执行此操作。
Is 0 a possible valid value for the column? If not, just typecast it to null when you encounter one. If it is valid you can still do that, by wrapping it in a conditional that checks the foreign row exists first.
一般来说,允许 FK 为空并不是一个好主意。 一些数据库(我知道 Oracle 是这样做的)通过将 FK 绑定到主键而不是其他表中的列来强制执行此操作。 您能否重构您的表,使该列不需要空值?
In general it's not a good idea to allow FKs to be null. Some databases (I know oracle does this) enforce this by tying FKs to primary keys rather than columns in other tables. Could you refactor your tables not to need nulls for that column?