You are correct but the rule is more complex to make it really work as expected. If you define your navigation property virtual
EF will at runtime create a new class (dynamic proxy) derived from your Brand
class and use it instead. This new dynamically created class contains logic to load navigation property when accessed for the first time. This feature is called lazy loading (or better transparent lazy loading).
What rules must be meet to make this work:
- All navigation properties in class must be
virtual
- Dynamic proxy creation must not be disabled (
context.Configuration.ProxyCreationEnabled
). It is enabled by default.
- Lazy loading must not be disabled (
context.Configuration.LazyLoadingEnabled
). It is enabled by default.
- Entity must be attached (default if you load entity from the database) to context and context must not be disposed = lazy loading works only within scope of living context used to load it from database (or where proxied entity was attached)
The opposite of lazy loading is called eager loading and that is what Include
does. If you use Include
your navigation property is loaded together with main entity.
Usage of lazy loading and eager loading depends on your needs and also on performance. Include
loads all data in single database query but it can result in huge data set when using a lot of includes or loading a lot of entities. If you are sure that you will need Brand
and all Products
for processing you should use eager loading.
Lazy loading is in turn used if you are not sure which navigation property you will need. For example if you load 100 brands but you will need to access only products from one brand it is not needed to load products for all brands in initial query. The disadvantage of the lazy loading is separate query (database roundtrip) for each navigation property => if you load 100 brands without include and you will access Products
property in each Brand
instance your code will generate another 100 queries to populate these navigation properties = eager loading would use just singe query but lazy loading used 101 queries (it is called N + 1 problem).
In more complex scenarios you can find that neither of these strategies perform as you need and you can use either third strategy called explicit loading or separate queries to load brands and than products for all brands you need.
Explicit loading has similar disadvantages as lazy loading but you must trigger it manually:
context.Entry(brand).Collection(b => b.Products).Load();
The main advantages for explicit loading is ability to filter relation. You can use Query()
before Load()
and use any filtering or even eager loading of nested relations.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…