我该如何解决外键约束错误 [英] How do i solve foreign key constraint error

查看:374
本文介绍了我该如何解决外键约束错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中插入超过200个字符的文本后,我仍然收到此错误.我已经尝试了一切.谁能帮我.我有两个表:角色和部门.角色表具有部门的主键作为外键,我已经设置了关系以允许这样做.我试图不强制使用外键约束,但是问题仍然存在.问题是,当我输入大约一两行文字时,它工作正常,但使用大文字时,它会弹出以下错误.两个表的两个主键都是int.

System.Data.ConstraintExceptoin:无法启用约束.一或多个行包含违反非空,唯一或外键约束的值.

I keep getting this error after inserting text with over 200 characters into my database. I ve tried everything. Can anyone help me please. i have two tables: roles and departments. the roles table has the departments primary key as a foreign key and i have set the relationship to allow for this. I have tried not to enforce foreign key constraints but the problem still persists. The thing is that when i enter about a line or two of text it works fine but with large text it pops up the error below. Both the primary keys of the two tables are int.

System.Data.ConstraintExceptoin: Failed to enable constraints. One or more rows contain values violating non-null, unique or foreign-key constraints

推荐答案

IMO,如果遇到此错误,则数据有问题.
您可以处理代码中的错误,然后优雅地退出代码.

但是,您应该寻找纠正此错误数据的方法,而不是修复错误.
外键概念背后的整个概念是防止错误的数据进入数据库并破坏它.
IMO, if you are getting this error, something is wrong with your data.
You can handle the error in your code, and step out of the code gracefully.

However, you should be looking at ways to correct this erroneous data rather than fix the error.
The entire concept behind the foreign key concept is to prevent wrong data from going into the database and corrupting it.


我在这里忙得不可开交:

可能是长字符串的该列被数据库列截断了.例如

这2个唯一的字符串:

aaaaaaaaaaaaaaaaaaaaaabbbbbb



aaaaaaaaaaaaaaaaaaaaaacccccc

如果存储到char(10)中,则将是非唯一的.因此,如果一个依赖于此列,则打破一个关键约束.
I''m going out on a limb here:

Perhaps that column that is a long string is getting truncated by the database column. For example

These 2 unique strings:

aaaaaaaaaaaaaaaaaaaabbbbbb

and

aaaaaaaaaaaaaaaaaaaacccccc

would be non unique if stored into a char(10). Thus breaking a key constraint if one is dependent on this column.


如果遇到此错误,则可能出现两种情况:
首先是您要存储的数据是错误的.
第二,您要存储的值或数据没有出现在您引用的另一个表的主键列中,


因此,首先尝试首先将数据插入主键,然后再插入外键.....




插入之前,请使用trim()方法...来修剪不必要的空间...
if u r geting this error then two case may arise :
1st is that the data that u r going to store is wrong.
second the value or data that u r going to store didn''t present in the primary key column of another table which u r refering,


so, at first try to insert data at first in primary key then in foreign key.....


or

before inserting use trim() method.... to trim the unwanted space...


这篇关于我该如何解决外键约束错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆