Should FK not null int have "0" as default value on dependent entity?
Added a relationship in an existing entity to another existing entity. The referenced entity (Country) has an int as primary key.
The updated entity (Distributor) gets the CountryID added, but the migration sets a default value of 0.
Technically, this makes sense because you'll have to have a default value, but since SqlServer starts autoincrementing int PK at 1 and since CountryID was defined as not nullable, this will ALWAYS generate an error in practice when you try to add the FK constraint - and in fact the SQL in the migration generates an error and the migration fails.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Distributor_Countries_CountryId". The conflict occurred in database "NewRevelarPortal", table "dbo.Countries", column 'Id'.
The generated SQL from the migration (captured with Profiler) is:
ALTER TABLE [Distributor] ADD [CountryId] int NOT NULL DEFAULT 0;
ALTER TABLE [Distributor] ADD CONSTRAINT [FK_Distributor_Countries_CountryId] FOREIGN KEY ([CountryId]) REFERENCES [Countries] ([Id]);
I haven't fully thought through this, but I think it would make sense to use a default of 1 in this case. It still might be invalid depending on the data, but at least it has a good chance of working whereas 0 is likely to always be wrong.
Maybe a separate issue, but what I also find interesting is that, in the initial migration, when it generated another entity pair Clinic/Location which has a similar FK relationship, no default value was set and the migration was successful. In that case, both entities were created at the same time in the same migration, whereas in this case I was adding a relationship to an existing entity. Is that because there was no data in the referenced table before, but now there is? In that case, I'd really expect to choose a value other than 0. (like the lowest existing value)
Again not really sure what I expect the behavior to be but certainly:
- consistent in both use cases - adding entities at the same time and updating existing entities
- not something that will [almost] always cause the migration to fail
Using RC2-16312.
When you add a non-nullable column we just set a default value of the CLR default for the type of the property. I don't think there is a good value we could pick for foreign key properties. I see what you are saying about there being a higher likelihood of there being a parent with and id of 1... but you could also argue that it's better to get an error so that you think about what parent you are actually hooking them up to.
We discussed at length and concluded that we just want to stick with the simple rule. Migrations are very much scaffolded code and we expect that folks will need/want to edit them in many cases.