❔ Can't seed one-to-many relation efcore
Hello, I am stuck on a error while trying to seed a database with Efcore.
DataContext.cs
User.cs
Post.cs
I have tried to put the Post inside of .OwnsMany, but that didn't work. How can I fix this?
18 Replies
It's never just "a error",
Its always important What error.
Could you share it in full?
Oh yeah sorry, forgot to share:
The seed entity for entity type 'Post' cannot be added because it has the navigation 'User' set. To seed relationships, add the entity seed to 'Post' and specify the foreign key values {'UserId'}. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values.
if you're trying to use skip navigations you cannot configure it as such.
if you want to use FKs like that, you need to declare a join table.
https://learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many it's all explained here.
Many-to-many relationships - EF Core
How to configure many-to-many relationships between entity types when using Entity Framework Core
But this is a One-to-many relation. I don't understand whats wrong with it.
= new()
you also really shouldn't do this on your nav props.Have you tried just using the User HasData()
And nesting a single user with it's post, leaving all ID-fields
null
? Curious if that would workapologies i misread as many:many - you should not be newing up user
it'll be setting the user id to 0 and thus be inserting a new user
well, in the case of string, won't at all
your nav props are set by EF or not at all.
Okay, thank you
Is this good?
Do you mean this?
that's fine
because I get the error
The seed entity for entity type 'List<Post>' cannot be added because no value was provided for the required property 'Capacity'.
i wouldn't seed data that way 😄
it needs an array, anyway
Well, that explains itself now doesn't it? =)
That's a whole other discussion I think,
Focusing on getting his code to work with minimal changes atm hehe
Oh sorry, yeah, that's true!
the user won't have an ID either, so you need to use the nav prop.
... ive been here long enough, thanks 😄
Thank guys, but I still can't get it working. That is probably because I still don't understand enough about EF. Will try to understand it first.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.