Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

entity framework - Is automapper preventing lazy loading with EF?

I have been using an AutoMapper and it seems that it gets me all the child entities (even if I don't specify them in "Include()" clause). Is there any way how to make lazy loading possible and get child properties only if I specify them.

Thank you,

Jakub

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After mapping you will have mapped object without any references to source entity (which holds database context for lazy loading). Only property values are copied to destination entity. So you will not be able to do any lazy-loading without source entity.

Actually lazy loading works just fine for you - and it's occur during mapping process. You specified mappings for lazy-loaded properties of your entity, and mapper tries to get those values. That results in lazy-loading all navigation properties which you have configured for mapping. This is very inefficient. To disable lazy-loading during mapping you can ignore navigation properties in mapping configuration. E.g. if you have customer with lazy-loaded orders:

Mapper.CreateMap<Customer, CustomerDto>()
      .ForMember(s => s.Orders, m => m.Ignore());

Or remove Orders property from your destination entity CustomerDto. If you need to have CustomerDto instance with orders inside, then best option is to do eager loading of orders, to avoid additional queries.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...