简体   繁体   中英

Return IQueryable from EF proxy object

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);

You could use the LINQ extension methode for this:

using System.Linq;

//....

x.YCollection.AsQueryable();

But then it would execute as LINQ to Objects instead of LINQ to Entities. So you could use this if you just needed a IQueryable object instead of needing it for performance issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM