我第一次使用 Entity Framework 并注意到实体对象返回实体集合。
DBEntities db = new DBEntities();
db.Users; //Users is an ObjectSet<User>
User user = db.Users.Where(x => x.Username == "test").First(); //Is this getting executed in the SQL or in memory?
user.Posts; //Posts is an EntityCollection<Post>
Post post = user.Posts.Where(x => x.PostID == "123").First(); //Is this getting executed in the SQL or in memory?
ObjectSet 和 EntityCollection 是否都实现了 IQueryable?我希望他们这样做是为了让我知道查询是在数据源而不是在内存中执行的。
编辑:所以显然 EntityCollection 不会,而 ObjectSet 会。这是否意味着我最好使用此代码?
DBEntities db = new DBEntities();
User user = db.Users.Where(x => x.Username == "test").First(); //Is this getting executed in the SQL or in memory?
Post post = db.Posts.Where(x => (x.PostID == "123")&&(x.Username == user.Username)).First(); // Querying the object set instead of the entity collection.
另外,ObjectSet 和 EntityCollection 有什么区别?他们不应该是一样的吗?
提前致谢!
编辑:对不起,我是新手。我试图理解。附加的 EntityCollections 是延迟加载的,所以如果我访问它们,那么内存中就会填充它们。而不是像我上次编辑那样对对象集进行两次查询,我很好奇这个查询是否更符合我的要求:
DBEntities db = new DBEntities();
User user = (from x in db.Users
from y in x.Posts
where x.Username == "test"
where y.PostID == 123
select x).First();
最佳答案
ObjectSet<T>
确实实现了IQueryable<T>
, 但是 EntityCollection<T>
才不是。
区别在于 ObjectSet<T>
旨在用于直接查询(这就是它实现接口(interface)的原因)。 EntityCollection<T>
另一方面,用于结果集的“多”端,通常在对 ObjectSet<T>
执行的查询中返回。 .因此,它执行 IEnumerable<T>
,但不是 IQueryable<T>
(因为它已经是查询的填充结果)。
关于linq - 您如何查询对象集并在同一查询中过滤附加的实体集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4683186/