简体   繁体   English

从EF代理对象返回IQueryable

[英]Return IQueryable from EF proxy object

Imagine I have the following DbSet : 假设我有以下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); 当我想检索X项目1时,我执行DbSet<X>.Find(1); which returns me an EF proxy object. 返回我一个EF代理对象。

Now that this proxy object ( X ) contains multiply Y 's I'd like to retrieve YCollection as a IQueryable<Y> . 现在,此代理对象( X )包含乘Y ,我想将YCollection检索为IQueryable<Y> (Mainly to do some additional filtering on it before retrieving it from the database.) (主要是在从数据库中检索它之前对其进行一些其他过滤。)

How can I retrieve YCollection as IQueryable<Y> ? 如何将YCollection检索为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: 您可以为此使用LINQ扩展方法:

using System.Linq;

//....

x.YCollection.AsQueryable();

But then it would execute as LINQ to Objects instead of LINQ to Entities. 但是随后它将作为LINQ to Objects而不是LINQ to Entities执行。 So you could use this if you just needed a IQueryable object instead of needing it for performance issues. 因此,如果您只需要一个IQueryable对象而不是因为性能问题而需要它,则可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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