❔ Querying Department Names using DepartmentID from User Queries
I'm attempting to query users based on their status, but I also want to display the department name associated with each user in the result. To accomplish this, I plan to use the department ID provided in the user query and perform a subsequent query to retrieve the associated department name. What approach would you recommend for achieving this?
17 Replies
I’d need to see more code. This more depends on how you’re DbContext, relationships, models, and current EF query are set up.
if there's a relationship between a user and a department that would probably be modeled in EF and you can just select the name out as part of the query
if you're not using EF, then a join in the same query instead of multiple queries
This is my Departments Model
This is the User
This the query
also, i don't recommend wrapping your dbcontext in a repository
a dbcontext is already a repository
All query should be on dbcontext?
it actually looks like you might have a repository in a service locator which is very sus to me
yes, there's no reason to wrap a dbcontext in another abstraction
if you used the context directly it would be trivial to include the department name in the query and map it directly to your DTO
Yes. they are on a Service class
that sounds like multiple layers of "don't do that"
why do you need a service locator when you already have DI?
Any possible way?
Okay, I will take note that. Thank you!
here's an example from one of my projects
i actually think those includes are unnecessary, just leftovers from a previous version (it should auto-include the navigation properties used in the
Select
call)Hmmm, I'll try to understand your code. Thank your providing from my reference.
I will transfer all my query inside DbContext first
How about this one ?
Protip: you don't need includes when you do a select
yeah i noticed the leftovers when i copied and pasted it here
bad. Tons of extra queries to the database
also: still using a service locator inside a DI container and wrapping the dbcontext in a repository
just inject the dbcontext directly and then you can write efficient queries
How can I check if the Department is Available?
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.