I am having a very peculiar problem: the ToList()
extension method is failing to convert results to a list. here is my code, standard boilerplate linq query, I converted ToList()
twice for good measure
var assets = new List<Asset>();
using (var ctx = new LeaseContext())
{
assets = ctx.Assets.OrderBy(o => o.Reference).Where(w => w.Status == AssetStatus.Active).ToList();
assets.ToList();
}
return assets;
yet the assets are still a list of System.Data.Entities.DynamicProxies
....
I've never had this problem before.
The reason is lazy loading. When lazy loading is enabled in EF (by default), then (again, by default) EF creates dynamic proxies for each entity. It's required for loading related entities. Dynamic proxy will be inherited from entity class. So in your case it will be inherited from Asset
. But dynamic proxy will have reference to the context which created its instance. And it will override navigation properties (which are virtual) to query entities via context which is stored in dynamic proxy.
And it's completely legal to add instances of derived types to list of base type.
If you don't want dynamic proxies, then just disable lazy loading and proxy creation:
ctx.Configuration.LazyLoadingEnabled = false; // turn-off loading on-demand
ctx.Configuration.ProxyCreationEnabled = false; // turn-off wrapper class generation
Technically you can just turn-off proxy generation and lazy loading will not work. But I prefer to turn-off both settings explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With