1
votes

I've got some data in my EF database. 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'; 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.

The question is: what should I do to bypass it? How can I add new Foreign key despite that?

2
when you change it in the edmx did you update / refresh the Entity..? let me know if I am understanding your issue correctly - MethodMan
I use EF Code First so I'm modifying model directly in code, not in edmx file - Piotrek

2 Answers

0
votes

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.

0
votes

This is not really an Entity Framework Code First issue, but a database issue.

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. Then, when applying the constraint, you will be attempting to relate a null to the Primary Key of the the parent table.

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).

Create the column without the relationship, populate the column with related values, and then add the constraint.