我理解OPs的挫败感,虚拟的这种使用并不是为了模板化抽象,而事实上的虚拟修饰符是有效的。
如果有人还在为这个问题而挣扎,我将提供我的观点,因为我试图保持解决方案的简单性,并将术语降至最低:
实体框架在一个简单的部分中确实利用了惰性加载,这相当于为将来的执行做准备。这符合“虚拟”修饰符,但还有更多。
在实体框架中,使用虚拟导航属性允许您将其表示为等同于SQL中的可空外键。在执行查询时,您不必急切地连接每个键表,但当您需要信息时——它就变成了需求驱动的。
I also mentioned nullable because many navigation properties are not relevant at first. i.e. In a customer / Orders scenario, you do not have to wait until the moment an order is processed to create a customer. You can, but if you had a multi-stage process to achieve this, you might find the need to persist the customer data for later completion or for deployment to future orders. If all nav properties were implemented, you'd have to establish every Foreign Key and relational field on the save. That really just sets the data back into memory, which defeats the role of persistence.
So while it may seem cryptic in the actual execution at run time, I have found the best rule of thumb to use would be: if you are outputting data (reading into a View Model or Serializable Model) and need values before references, do not use virtual; If your scope is collecting data that may be incomplete or a need to search and not require every search parameter completed for a search, the code will make good use of reference, similar to using nullable value properties int? long?.
Also, abstracting your business logic from your data collection until the need to inject it has many performance benefits, similar to instantiating an object and starting it at null. Entity Framework uses a lot of reflection and dynamics, which can degrade performance, and the need to have a flexible model that can scale to demand is critical to managing performance.
对我来说,这总是比使用过多的技术术语(如代理、委托、处理程序等)更有意义。一旦你接触到第三或第四个编程语言,这些就会变得很混乱。