❔ User relations and retrieving that data in Razor Pages
I come from a Laravel (PHP) and JS/TS background. Assume I have a
Todo
index page and I want to fetch all Todos belonging to the currently active user. In something like Laravel I'd simply do something like user()->todos()->all()
or potentially Todos::where('user_id', user()->id)
.
I apparently do not have access to the user's ID in User
or User.Identity
... only their name (?). And I also cannot do User.Todos
like I can do Todo.User
.
What am I missing here? I'm finding it very difficult to find resources on this when compared to other frameworks like Laravel10 Replies
You're looking at using EF Core
You probably want to
.Select()
it into a DTO class so you're not operating on raw database entities too
To get currently logged-in user's ID you can use
Finding the latter was just first result for asp core get user id
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
i'm going to be doing this all over my codebase (or adding some middleware or something). I assumed this was a pretty trivial and built in thing that happens all the time in application logic and would just be includedMake an extension method on whatever type
User
is that's, say, GetId()
and you can shorten it a lot
Or make your own controller class that gets the ID in the ctor and inherit all your other controllers from this classok. thank you! i'll look into all this. just didn't want to reinvent something that already existed. Any idea why I can't just do
User.Todos
or where to look at an example repository for that? My ApplicationUser
model has the relationYou can't do
User.Todos
because it's not loaded from the database
User
in this context is not your user class, it's a collection of claims
So stuff that's saved in the session/cookie/JWT/whatever
If you want to fetch the actual user from the database, you need to do sook. makes some sense. i assumed i'm hitting the database to verify the cookie/session or whatever
thank you
helps me to understand what's actually going on under the hood
EF Core mostly just uses LINQ and translates it to SQL
So as long as you know LINQ, you know EF
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.