AutoMapper and Entity Framework POCO with explicit loading

I explicitly upload relationships to my POCO when I need it, but since I switched to AutoMapper, I thought I could instruct it to preload the relationships for me so that my code in the service layer looks cleaner:

Mapper.CreateMap<Issue, IssueEditModel>().BeforeMap((i, m) => LoadProperties<Issue>(() => { return kernel.GetService<IIssuesRepository>(); }, i, new Expression<Func<Issue, object>>[] { e => e.RelationshipA, e => e.RelationshipB } ) ); 

The LoadProperties method scans the repository using DependencyResolver and loads the listed relationships using the ObjectContext LoadProperty method. Now my services can easily map EF POCO to view the model with a single call to Mapper.Map.

Has anyone tried this before? What are the potential pitfalls? Does it make sense to keep all these LoadProperty calls in your service / repository layers and keep AutoMapper mappings as simple as possible?

My concern is that AutoMapper can do a lot of tedious work for you, like converting types and finding objects by identifiers when converting from a view model to POCO, but at the same time it moves this β€œlogic” from your service / repository to configure AutoMapper. If you have much experience with this, please share your thoughts.

+2
source share
1 answer

I read more about developing and working with domains in your web application, and now I understand that I have abused AutoMapper. Just because I can do this does not mean that I have to. One of the pitfalls is testing. Since my AutoMapper calls get into the database to resolve some relationships, I cannot use these mappings for unit testing, I need to create another set of mappings just for my test.

Your repositories must preload the necessary relationships. People suggest that methods accept flags that control whether certain relationships should be loaded using Include. In my case, I think that I will always load a one-to-one relationship when the entity is on the side and all the relationships when receiving a single object (for example, for a detailed view).

0
source

Source: https://habr.com/ru/post/1341086/


All Articles