none
Enable Lazy Loading for Navigation Properties on Entities in EF 5 RRS feed

  • Question

  • I'm trying to understand how can I have a lazy loading  instantiated in my domain model...

    i have a very simple Domain Model, I have three tables which are related with either other:

    Campus===>Building===>Floor (like a cascading dropdownlist)

    I have POCO classes

    public partial class Campu
        {
            public int CampusId { get; set; }
            public string Text { get; set; }

            public virtual ICollection<Building> Buildings { get; set; }

            public Campu()
            {
                this.Buildings = new HashSet<Building>();
            }

        }

    using System;
        using System.Collections.Generic;

        public partial class Building
        {
            public int BuildingId { get; set; }
            public int CampusId { get; set; }
            public string Text { get; set; }

            public virtual Campu Campu { get; set; }
            public virtual ICollection<Floor> Floors { get; set; }
        }

         public class Floor
        {
            public int FloorId { get; set; }
            public int BuildingId { get; set; }
            public int CampusId { get; set; }
            public string Text { get; set; }

            public virtual Building Building { get; set; }
        }

    What would I need to enabled lazy loading?

    my DB Context looks like this:

    public partial class myproj_dbEntities : DbContext
        {
            public myproj_dbEntities() : base("name=connectionstring_dbEntities")
            {

            }
        
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                throw new UnintentionalCodeFirstException();
            }
        
            public DbSet<Building> Buildings { get; set; }
            public DbSet<Campu> Campus { get; set; }
            public DbSet<Floor> Floors { get; set; }

        }

    Wednesday, September 25, 2013 12:37 PM

Answers

  • For EF to enable lazy loading for POCO entities, it creates a proxy class around the POCO entity at runtime.

    For the lazy loading to work, those related properties that you want to be lazily loaded must be marked as virtual and those who point to a set of related child objects have to be of type ICollection. There is a complete list of the requirements for POCO proxies to be created available on MSDN here: http://msdn.microsoft.com/en-us/library/vstudio/dd468057(v=vs.100).aspx

    Also, the Configuration.LazyLoadingEnabled and Configuration.ProxyCreationEnabled properties of the DbContext must be set to true which they are by default.

    Wednesday, September 25, 2013 1:01 PM