SoFunction
Updated on 2025-03-06

Entity Framework master-slave table data loading method

1. LazyLoading

With lazy loading, the associated entity must be marked virtual.

This example is to label Lodgings in the Destination class as virtual. Because first send SQL to query the primary key object, and then check the associated data from the table based on the primary key id.

    private static void TestLazyLoading()
    {
        using (var context = new ())
        {
           var canyon = (from d in  where  == "Grand Canyon" select d).Single();

           var distanceQuery = from l in    // Lazy loading of all .Lodgings of canyon                                where  == "HuangShan Hotel"
                                select l;
            foreach (var lodging in distanceQuery)
                ();
        }
    }

Improvement: Operate in the database, display loading

    private static void QueryLodgingDistancePro()
    {
        using (var context = new ())
        {
            var canyon = (from d in  where  == "Grand Canyon" select d).Single();
            var lodgingQuery = (canyon).Collection(d => ).Query();//The next query is in the database, including Count(), etc.            var distanceQuery = from l in lodgingQuery 
                                 where  == "HuangShan Hotel" 
                                 select l;

            foreach (var lodging in distanceQuery)
                ();
        }
    }

2. Greed Loading: EagerLoading

    private static void TestEagerLoading()
    {
        using (var context = new ())
        {
            // var allDestinations = (d => );
            var AustraliaDestination = (d => ).Where(d =>  == "Bali");
            //(l => );
            //(d => (l => ));
            //(l => ).Include(l => );
            foreach (var destination in AustraliaDestination)
            {
                foreach (var lodging in )
                    (" - " + );
            }
        }
    }

3. Display loading: ExplicitLoading

1. Find the navigation attributes of a collection

    private static void LoadRelateData()
    {
        using (var context = new ())
        {
           var canyon = (from d in  where  == "Grand Canyon" select d).Single();

           (canyon).Collection(d => ).Load();  //Show loading
           foreach (var lodging in )
                ();
        }
    }

2. Find the navigation attribute of an entity object

    private static void LoadPrimaryKeyData()
    {
        using (var context = new ())
        {
            var lodging = ();

            (lodging).Reference(l => ).Load();

           foreach (var destination in )   //It is traversing the Destinations data in memory                ();
        }
    }

This is what this article about the data loading of Entity Framework master-slave tables. I hope it will be helpful to everyone's learning and I hope everyone will support me more.