简体   繁体   English

更改外键:无法将值NULL插入列

[英]Changing the foreign key: Cannot insert the value NULL into column

I've got some data in my EF database. 我的EF数据库中有一些数据。 I want to change the foreign key in one of my classes: 我想在我的课程之一中更改外键:

[ForeignKey("Collection")]
public int CollectionID { get; set; }

Unfortunately I get this error 不幸的是我得到这个错误

Cannot insert the value NULL into column 'CollectionID', table 'WebLanguageTeacher1.dbo.Words'; 无法将值NULL插入表'WebLanguageTeacher1.dbo.Words'的列'CollectionID'中; column does not allow nulls. 列不允许为空。 UPDATE fails. 更新失败。

when I try to add new migration to my database. 当我尝试向数据库中添加新的迁移时。 It's understandable: foregin key can't be null, when I create new column in my db, Entity Framework creates new NULL cells. 这是可以理解的:foregin键不能为null,当我在数据库中创建新列时,Entity Framework将创建新的NULL单元格。

The question is: what should I do to bypass it? 问题是:我应该怎么做才能绕过它? How can I add new Foreign key despite that? 尽管如此,如何添加新的外键?

I have previously had a similar scenario though it was a Primary Key in my case. 我以前也有过类似的情况,尽管在我的情况下这是主键。

I by-passed that by editing the migration scripts. 我通过编辑迁移脚本来绕过它。

This is not really an Entity Framework Code First issue, but a database issue. 这实际上不是Entity Framework Code First问题,而是数据库问题。

If you try to add a column to a table, and then add the Foreign Key Constraint with the Primary Key table, you would get the same error. 如果您尝试向表中添加一列,然后将外键约束与主键表一起添加,则会出现相同的错误。

The reason is that you have created the column with null as the default value for every existing record. 原因是您创建的列以null作为每个现有记录的默认值。 Then, when applying the constraint, you will be attempting to relate a null to the Primary Key of the the parent table. 然后,在应用约束时,您将尝试将null与父表的主键相关联。

So, the solution is one of several options: 因此,该解决方案是以下几种选择之一:

If the current data is not required (initial development of the app), then clear the data - this will allow the relationship to be created and will only take effect when adding data. 如果不需要当前数据(应用程序的初始开发),请清除数据-这将允许创建关系并且仅在添加数据时生效。

Set a default value for the new column that has an existing value in the parent table so that no records will not fail to find a parent key value. 为在父表中具有现有值的新列设置默认值,以使所有记录都不会找不到父键值。 So, if you know there will always be a value of '1' in the parent table, you could use '1' as the default (only a temporary solution - would allow invalid data in the future of a live app). 因此,如果您知道父表中始终有一个值“ 1”,则可以将“ 1”用作默认值(只有一个临时解决方案-将来会在实时应用程序中允许使用无效数据)。

Create the column without the relationship, populate the column with related values, and then add the constraint. 创建没有关系的列,用相关值填充该列,然后添加约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM