locked
Entity Framework - how to load items in related table where id matches OR id equals null? RRS feed

  • Question

  • User-1760640578 posted

    My main table is called Plant.  The other table I have is Document.   Each Document has a PlantId, however, the PlantId in the Document table can be null which indicates to the software that particular Document is for all plants.  When I query GetPlantById it “lazy-loads” the related Documents (the Documents where PlantId = 1 for example) but I also need it to load the documents where the PlantId is null.  How can I achieve this?

    Monday, November 21, 2016 2:36 PM

Answers

  • User-1760640578 posted

    Ok.  I managed to get it to work.  I would be interested in feedback though to see if my solution is the correct one. 

    I removed the virtual keyword from the Document object in my Plant class.  This turns off lazy loading.  Then in my PlantRepository I created a new method called LoadPlantData.  In LoadPlantData I am explicitly loading the Document object.

            public Plant LoadPlantData(int plantId)
            {
                //load the plant object
    
                //I removed the virtual property from the Document object in the Plant class so the entities are not lazy loaded.
                var plant = DbContext.Plant.First(s => s.PlantId == plantId);
    
                //now I explicitly load exactly what I want
                plant.Document = DbContext.Document.Where(a => a.PlantId == null || a.PlantId == plantId).ToList();
    
                return plant;
            }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 21, 2016 4:35 PM