Return IQueryable from EF proxy object

c# entity-framework entity-framework-6 linq-to-sql

Question

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>?

1
1
7/10/2015 3:05:45 PM

Accepted Answer

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);
3
8/11/2017 1:32:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow