C
C#3w ago
workani

✅ How to avoid creating same CRUD Commands/Queries for different entities | MediatR, ASP.NET

Hi, right now I’m creating same CRUD Commands/Queries(e.g. GetAll or DeleteById) for each new entity in my project. How to avoid that?
18 Replies
Mayor McCheese
You probably could use a source generator.
SleepWellPupper
You could also use generics:
class GetAllQuery<T>;
record GetAllResponse<T>(IReadOnlyList<T> Entities);
class GetAllQuery<T>;
record GetAllResponse<T>(IReadOnlyList<T> Entities);
That is, create a set of generic crud commands/queries and then use them with the entity type you're interested in at the time.
workani
workaniOP3w ago
I’ve already tried that, but it didn’t work out because I had three generic parameters: class GetById<T, TDto, TId>; and I wasn’t able to register it in the DI. What do you mean ?
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View
FestivalDelGelato
what type of project is this? because there's a good chance you shouldn't be creating all these models for all your entities source: went through it
workani
workaniOP3w ago
Admin panel for offline book shop The thing is, I’m getting an error after trying to register service with 3 generic parameters
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View
workani
workaniOP3w ago
services.AddTransient(typeof(IRequestHandler<,>), typeof(GetAllEntites<,,,>); This lines causes an error
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View
workani
workaniOP3w ago
Most likely, cause I got a bit lost with generics That would be hard to do, cause I’ve deleted all generic queries/handlers
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View
workani
workaniOP3w ago
And which exact part of code do you need ?
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View
workani
workaniOP3w ago
Let me ask different question, what are my options to avoid creating CRUD commands/queries each time?
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View
workani
workaniOP3w ago
I use EFCore + Automapper So the best way is to create commands/handlers for each entity? + Generic repository
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View
workani
workaniOP3w ago
Fair enough, thanks!

Did you find this page helpful?