开发者

AutoMapper and Entity Framework POCO with explicit loading

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 Ex开发者_如何学编程pression<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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜