C# 建筑IQueryable<;T>;然后将其连接到DbSet<;T>;

C# 建筑IQueryable<;T>;然后将其连接到DbSet<;T>;,c#,database,linq,linq-to-sql,entity-framework-core,C#,Database,Linq,Linq To Sql,Entity Framework Core,我的问题是 我可以不使用DbSet构建IQueryble吗 然后将IQueryable传递给将IQueryable附加到DbSet的方法 例如: public class Querying<T> { public T BuildQuery() { return Enumerable.Empty<T>().AsQueryable().Where(...); } }

我的问题是 我可以不使用
DbSet构建
IQueryble
吗 然后将
IQueryable
传递给将
IQueryable
附加到
DbSet
的方法

例如:

    public class Querying<T>
    {
         public T BuildQuery()
         {
            return Enumerable.Empty<T>().AsQueryable().Where(...);
         }
    }

    public class DatabaseContext<T>:DbContext
    {
        DbSet<T> _set;
        public List<T> ExecuteQuery(Querying<T> query)
        {
              return _set.AttachQuery(query.BuildQuery()).ToList();
        }
    }
公共类查询
{
公共构建查询()
{
返回可枚举的.Empty().AsQueryable().Where(…);
}
}
公共类DatabaseContext:DbContext
{
DbSet_集;
公共列表执行器(查询)
{
return _set.AttachQuery(query.BuildQuery()).ToList();
}
}
使用系统;
使用System.Linq;
使用System.Linq.Expressions;
命名空间查询测试
{
内部静态类程序
{
私有类替换ConstantVisitor:ExpressionVisitor
{
公共对象OldValue{get;}
公共对象NewValue{get;}
公共替换ConstantVisitor(对象旧值、对象新值)
{
OldValue=OldValue;
NewValue=NewValue;
}
受保护的重写表达式VisitConstant(ConstantExpression节点)
{
如果(node.Value==OldValue)
{
返回表达式.Constant(NewValue);
}
返回base.VisitConstant(节点);
}
}
公共静态IQueryable替换源(此IQueryable查询,IQueryable源)
{
var exp=query.Expression;
while(exp是MethodCallExpression m)
{
exp=m.Arguments[0];
}
如果(!(exp是恒定压力oldSource))
{
抛出新ArgumentException();
}
var newExp=new replaceContvisitor(oldSource.Value,source.Visit)(query.Expression);
返回source.Provider.CreateQuery(newExp);
}
内部静态void Main(字符串[]args)
{
var oldSource=newint[]{}.AsQueryable();
变量查询=
从我在oldSource
其中i>5
选择$“{i*2}”;
var newSource=newint[]{1,3,5,7,9}.AsQueryable();
var newQuery=query.ReplaceSource(newSource);
Console.WriteLine(string.Join(“,”,newQuery));//14,18
}
}
}

是的,您可以这样做,请看一看否,我不想将DbSet作为IQueryable发送,这意味着无论收到什么,它可以执行我想要的是启动iQueryTable,然后将其发送到某个类执行。我得到了以下异常:InvalidOperationException:源iQueryTable的提供程序没有实现IAsyncQueryProvider。只有实现IEntityQueryProvider的提供程序才能用于实体框架异步操作。然后我改为Count而不是CountAsync,当数据库中的记录超过10k时,我得到了0