实体框架 4:为什么我无法获取派生实体的 ObjectSet 而不是 ObjectQuery?
我有一个派生自“BaseEntity”的“投资”实体。
使用 _container.BaseEntities.OfType
我得到一个始终查询数据库的 ObjectQuery。
因此我宁愿有一个ObjectSet
。
我不明白为什么 EF 不支持派生实体的这一点...或者是吗? ;)
如果我继续在 EF 中创建一个与所有派生实体关联的“根实体”(这很愚蠢),我将通过该根实体的导航属性获取这些实体的 EntityCollections。但一定还有另一种方法......
干杯
I have an "Investment" entity that is derived from "BaseEntity".
With _container.BaseEntities.OfType<Investment>()
I get an ObjectQuery that always queries the database.
Therefore I would rather have an ObjectSet<Investment>
.
I can't understand why EF doesn't support this for derived entities... Or does it? ;)
If I would go ahead and create a "root entity" in EF (which would be silly) that has associations to all my derived entities, I would get EntityCollections for those entities through the navigation properties of that one root-entity. But there must be another way...
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是 EF ObjectContext API 中的工作原理。如果您尝试为派生实体创建
ObjectSet
,您将得到:此外,一旦定义了继承,就不再有派生实体的导航属性。提供导航属性的关联更改为继承。
我还关注了您的以前的问题 这可能是这个的来源,我不得不说我尝试了很多,但我永远无法理解你的行为。即使我直接调用 Count 到
ObjectSet
,我总是会得到 SQL 查询(在探查器中检查)和数据库中的实体计数 - 而不是集合中的实体计数。That is how it works in EF ObjectContext API. If you try to create
ObjectSet
for derived entity you will get:Also once you define inheritance there are no navigation properties to derived entities. The association which offers navigation property is changed to inheritance.
I also followed your former questions which is probably source of this one and I have to say I tried a lot but I can never get your behavior. Even if I call Count directly to
ObjectSet
I always get SQL query (checked in the profiler) and count of entities in the database - not in the set.ObjectQuery
并不总是查询数据库。它只是一个查询规范 - 在本例中是返回Investment
类型的所有 BaseEntities 的规范。您可以使用其他过滤器或 orderby 子句或投影等来组合它。数据库中不会执行任何操作,除非您应用一些贪婪运算符,例如ToList()
或First()
等,或者直到您应用 foreach 循环来获取结果。ObjectQuery<T>
does not always query the database. It is only a query specification - in this case a specification to return all BaseEntities of typeInvestment
. You can compose it with additional filters or orderby clauses or projections and so on. Nothing is executed in the database until you apply some greedy operator likeToList()
orFirst()
etc. or until you apply a foreach loop to fetch the results.