Reputation: 1631
In a simple web API call to receive some data, I set db.Configuration.LazyLoadingEnabled = false;
. Then I retrieve elements from the database via Entity Framework. These are converted into an exchange object using an explicit cast. This exchange class in turn contains conversions using an explicit cast again. Now I would like to know within such a cast method whether lazy loading is active or not, without knowledge of the actual database context. Is there a way to determine this using only the proxy object?
The reason is that I would like to set a list of child elements in my exchange object to NULL if it was not loaded in the proxy object. However (according to my observation) the lists are simply created empty with zero child elements. As a result, I cannot see exactly whether there are actually no assigned children in the database, or whether the data has not been loaded at all. Is there a reliable way to find this out?
public async Task<IEnumerable<Models.DataExchange.Plant>> GetPlantsWithStorages() {
db.Configuration.LazyLoadingEnabled = false;
// Get list from database
List<Models.Plant> plantList = await db.Plants
.IncludeOptimized(plant => plant.PlantAreas)
.IncludeOptimized(plant => plant.PlantAreas.Select(plantArea => plantArea.Storages))
.IncludeOptimized(plant => plant.PlantAreas.Select(plantArea => plantArea.LoadingBays))
.OrderBy(plant => plant.Name)
.ToListAsync();
// Cast and return result to client
return plantList.Select(p => (Models.DataExchange.Plant)p);
}
public static explicit operator StorageLocation(Storage storage) {
if (storage == null)
throw new ArgumentNullException(nameof(storage));
// storage.ChargeCarrier_Storage won't be filled in my example.
// However, the list is not null, but an empty list.
// Is there something like storage.ChargeCarrier_Storage.IsLoaded?
return new StorageLocation() {
Description1 = storage.Description1,
Description2 = storage.Description2,
ID_Storage = storage.ID,
ID_StorageType = storage.ID_StorageType,
ChargeCarriers = storage.ChargeCarrier_Storage?.Select(ccs => (ChargeCarrier)ccs.ChargeCarrier)
};
}
Upvotes: 0
Views: 24
Reputation: 89051
without knowledge of the actual database context. Is there a way to determine this using only the proxy object?
You can examine the runtime type of the entity. It will be a proxy type, from a dynamic assembly, isntead of an Entity type from the Assembly that defines your Entities. Eg
bool IsProxy(object entity)
{
return System.Reflection.Assembly.GetExecutingAssembly() != entity.GetType().Assembly;
}
I cannot see exactly whether there are actually no assigned children in the database, or whether the data has not been loaded at all. Is there a reliable way to find this out?
The right way to do that is through the DbContext. eg
var areasLoaded = db.Entry(plant).Reference(a => a.PlantAreas).IsLoaded();
Upvotes: 1