Last post Nov 21, 2016 04:35 PM by MelissaLynn
Nov 21, 2016 02:37 PM|MelissaLynn|LINK
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?
Nov 21, 2016 04:35 PM|MelissaLynn|LINK
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();