Search code examples
entity-frameworkasp.net-web-api2lazy-loadingeager-loading

Combining lazy and eager loading in EF


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?


Solution

  • 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
            }
    }