Setting a Default Value for Migrations
I have a relationship between two models but the relationship is not required, i.e. the first model which "belongs to" the other model can exists on its own.
So in essence, class
Item
can stand on its own but it can also belong to someone.
I am getting this when trying to run the database update command for the seed data which has set the OwnerId to 0
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Items_Owners_OwnerId". The conflict occurred in database "<DB>", table "dbo.Owners", column 'Id'.
32 Replies
The reason I am doing this is there are "global" Items that can be utilized by anyone, but some items belong to specific people. These items are only accessible to them but not others.
your OwnerId should be NULL, not 0
Can it be zero?
not with a
int?
OwnerId
the default value for that is NULLHmmmm
Let me try
which is what is used for relation ships by your database provider
No go
I still get the error
and the migration still puts 0 as a default value
well, thats what you specified via attribute
0 in a nullable column thats a foreignkey means, that there needs to be an entry on the other side of that relationship which has the primary key value of 0
I already put null as the default value
why do you even set that, just remove the attribute
i just updated the value from 0 to null
but lemme try removing it
Same problem
Hmmmm
then idk. probably something else is wrong aswell
this should work
Do you have Id column in Owner?
Yes.
100% positive
I also checked the migrations generated
If it helps, the seed data with 0 OwnerId is my only problem
All the other seed data that has an ownerId of > 0 is fine
Paste the code of your Owner class?
if just your seed data is wrong, then correct your seed data and set the ownerid to NULL in there
That's actually my last result but I want to solve this on code level first if possible
this is the code lvl
If and when someone decides to regenerate the migrations from scratch, this problem won't exist (if I solve it)
Migrations are generated from the model code on a code first approach
So yeah
Oh you are saying you putting 0 as seed
Yes.
Why not null?
That's also an option, but I'd rather have a place holder value for "global" items
As a seed
instead of null, for sanity purposes
0 is valid ID
So it will try to find a Owner with ID 0
OHH
And validation fails
THAT MAKES PERFECT SENSE
HOLD ON
lol
Quirky
let me try a different approach