Multiple 1 to Many Relationships in Entity Framework
Hello, I just am looking on getting some documentation or something on entity framework core. I have a main Project Table, this Project Table has many tables connected like Tasks, Users, Clients, Phases, etc. All of these other tables are 1 to Many so my projects has a lot of 1 to many relationship(1 project has many tasks, and a task only has 1 project). I'm struggling to figure out how to do this. Any documentation or resources would be awesome!
17 Replies
So a project has many tasks, and many users, and many clients, etc?
It's the same way you do a single one to many relationship, you just do it multiple times
Yeah I tried that but it just isn't happy. I'll get you an error code one sec
AppDBContext :
So I have Phases, that is working all good. So I pretty much copied the exact thing for Tasks. But even with adding onModelBuilder it's still pissed hahaha
what do your entities look like? https://learn.microsoft.com/en-us/ef/core/modeling/relationships/one-to-many
One-to-many relationships - EF Core
How to configure one-to-many relationships between entity types when using Entity Framework Core
The error indicates you're trying to insert null into a non-nullable column
namely
TasksID
Right that's where I'm confused cause the code is the same as phases(just replaced as tasks)
It looks like it's the primary key of the
Tasks
table, which should indeed not be nullable
What insert statement is causing the error?tasks it like won't auto increment the ID like the phases
Also, you should name your classes in the singular form
e.g.
Project
instead of Projects
Ik I got too deep into it and I'm gonna have to go back and rebuild it so I'm just trying to get the linking down
But you're def right haha
Ik it's super confusing but maybe should I just share a git link cause I got repository/interfaces/dto/mappers/controllers that all connect. I'm thinking i'm beefing something up
To start all we need is the stack trace of that exception to see what caused it
It's really weird that it's being thrown, because the property is a non nullable value type, so EF shouldn't be sending a query that tries to insert null into that column
that's the full error
so what's happening at TasksRepository.cs:line 28
It's also worth noting that your dbcontext is itself a repository, and you don't need to layer another one on top of it
Put a breakpoint in and examine the properties of
tasksModel
See what the value of TasksID
is
Though it's impossible for it to be null, so I'm honestly not sure what's going on
Also don't use AddAsync()
so that from the Phases works totally fine. It's not until I add the tasks to the repo. Trying out the breakpoint to see if it can give me the deats though
So it just works now, idk I didn't do anything. Redid the migration a few times after testing a few things and it just works..