AutoMapper and Entity Framework POCO with explicit loading

送分小仙女□ 提交于 2019-12-10 11:22:33

问题


I explicitly load relationships on my POCO when I need to, but since I switched to AutoMapper I thought I could instruct it to pre-load relationships for me so that my code in 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 looks up the repository using DependencyResolver and loads listed relationships using ObjectContext's LoadProperty method. Now my services can easily map EF POCO to view model with a single Mapper.Map call.

Has anyone tried this before? What are 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?

What bothers me is that you can make AutoMapper do a lot of tedious work for you like converting types and looking up entities by IDs when converting from view model to POCO, but at the same time this moves this "logic" from your service/repository to AutoMapper configuration. If you have extensive experience with this please do share your thoughts.


回答1:


I've been reading more on domain driven design and responsibilities of layers in your web application and now I realize I have been abusing AutoMapper. Just because I can make it do these things doesn't mean I should. One of the pitfalls is testing. Because my calls to AutoMapper end up hitting the database to resolve some relationships I cannot use these mappings for unit-testing, I have to create a different set of mappings just for my test.

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



来源:https://stackoverflow.com/questions/6933519/automapper-and-entity-framework-poco-with-explicit-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!