Imagine I have the following DbSet
:
public class X {
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Y> YCollection { get; set; }
}
When I want to retrieve item 1 of X
I execute DbSet<X>.Find(1);
which returns me an EF proxy object.
Now that this proxy object (X
) contains multiply Y
's I'd like to retrieve YCollection
as a IQueryable<Y>
. (Mainly to do some additional filtering on it before retrieving it from the database.)
How can I retrieve YCollection
as IQueryable<Y>
?
There's no way to do this directly off the entity itself that I'm aware of, but you can use the context itself to form the query:
var x = context.DbSet<X>.Find(1);
var query = context.Entry(x).Collection(x => YCollection).Query();
I suppose this could be wrapped up in an extension method to be used like:
x.YCollection.AsQueryable(context);