如何查询对象集并在同一查询中筛选附加的实体集合?

Che*_*hev 5 linq linq-to-entities entity-framework entity-framework-4

我第一次使用实体框架,并注意到实体对象返回实体集合.

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?
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

另外,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();
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 3

ObjectSet<T>执行IQueryable<T>,但EntityCollection<T>没有执行。

不同之处在于它ObjectSet<T>旨在直接用于查询(这就是它实现该接口的原因)。 EntityCollection<T>另一方面,用于结果集的“多”端,通常在ObjectSet<T>. 因此,它实现了IEnumerable<T>,但没有IQueryable<T>(因为它已经是查询的填充结果)。