1
votes

I am wondering if it is possible combining lazy and eager loading. For example, I have one Web Api controller with GET method that does not need to load related entity data, but I have also another Web Api controller and its method GET needs to retrieve data from related entity.

Is it good practice to combine these two approaches and are there any specific configurations I need to set up?

1
It is possible to combine those two, but your specified scenarios can be done using eager loading only. If possible, it's much better to stick to only one approach. - Red
I'm wondering if this question might be a little more opinion-based than "good practice" based... - Geoff James
Of course it's opinion-based. How can we recommend any good practice without knowing any requirements? - Gert Arnold
There is not need to have any requirements, I am just wondering if I have 100 Web Api controllers and each of them has its own GET method, and 50 of them need to retrieve related entities and other 50 does not. How can I achieve so that my application works as fast as it possible. - ruud
The answer to that is different for each case. So there's your answer: yes it is good practice to combine loading strategies. - Gert Arnold

1 Answers

2
votes

Yes you can do that.And it's a Good practise too according to the real situation like yours.

When you don't need the Lazyloding ,on that particular method you can disable it as shown below.

public List<PropertyListDto> SearchProperties(AdditionalSearchInput input)
{
   _context.Configuration.LazyLoadingEnabled = false;//to remove lazy loading

  ///your code
}

Note : In Entity Framework 4 and beyond Lazy Loading is enabled by default. We can disable it globally, on DbContext level, or selectively, on query level as shown above.

Here is how to do it on DbContext level.

public partial class MyDBEntities : DbContext
    {
        public MyDBEntities(): base("name=MyDBEntities")
        {
            this.Configuration.LazyLoadingEnabled = false;
        }
    }

Update : The 50 controllers where you don't need lazyloding you can disable it on constractor level as shown below.Then you don't need to give it on query level on each method.I think it's very quick way to implement it :)

public class YourAppService : IYourAppService
    {
        private readonly YourDbContext _context;

        public YourAppService(YourDbContext context)
        {
            _context = context;
            _context.Configuration.LazyLoadingEnabled = false;//to remove lazy loading
        }
}