JonPSmith / EfCore.GenericServices

A library to help you quickly code CRUD accesses for a web/mobile/desktop application using EF Core.
https://www.thereformedprogrammer.net/genericservices-a-library-to-provide-crud-front-end-services-from-a-ef-core-database/
MIT License
601 stars 94 forks source link

Add `ICrudServices.MapEntityToDto()` #72

Closed aaron-kruse closed 1 month ago

aaron-kruse commented 1 month ago

Add ICrudServices.MapEntityToDto()

Exposes a new method that can be used to map an existing entity instance to a DTO using the same mapping config that ReadSingle() would use.

Description

We're using GenericServices in our project to retrieve entities and map them to DTOs, sometimes using PerDtoConfig when needed. Using ReadSingle() and ReadManyNoTracked() work great for most scenarios, but we sometimes run into scenarios where with entities directly. These changes will allow us to continue to use GenericServices to handle mapping an entity to a DTO, even when GenericServices wasn't used to retrieve the data.

One example use case is using static factory methods to get back an instance of an entity with default values assigned. Since this instance isn't persisted anywhere, GenericServices can't be used to retrieve and map it (ex. via ReadSingle()). These changes make this possible by calling MapEntityToDto and passing in the entity instance to map.

Notes

No promises on code quality or placement 🤫 but it is functional and all tests pass. I started by looking at ReadSingle() and ProjectFromEntityToDto() and essentially swapping out the IQueryable requirement that retrieves an entity with one that is passed in, so I put the new method in the same area. Somewhere in the process I came across MapDtoToEntity() so I thought that was a reasonable place to add a new MapEntityToDto().

aaron-kruse commented 1 month ago

Hopefully I'm not overstepping any boundaries, we had a need for this so I looked into it then thought I'd share so it could hopefully be included in the official package and others might also find it useful. If you have any feedback or would like any changes, just let me know!

JonPSmith commented 1 month ago

Hi @aaron-kruse,

You might not know, but I have dementia - see this section, which means I rarely change any of my libraries that. So, I'm sorry to say that I won't your pull because I then have to manage your code going forward.

aaron-kruse commented 1 month ago

Thanks for the response, and sorry to hear about your diagnosis. No problem at all about the pull request, I completely understand your position on maintaining the library.

I appreciate you taking the time to explain and provide some guidance for going forward, and I wish you all the best.