我可以引用编译查询作为编译查询的数据源吗?

时间:2009-09-10 20:10:22

标签: c# .net linq

最好在代码中描述这个...

我有这个

public class A<T>
{
     public static class Queries
     {
          public static Func<DataContext, int, T>Get =
                CompiledQuery.Compile<DataContext, int, T>(
                    (DataContextdb, int i) => (from t in db.GetTable<T>()
                                                      where t.ID == i
                                                      select t).SingleOrDefault());
     }
}

我可以创建一个新的类和查询,就像这样...

public class B<T>:A<t>
{
      public static class BQueries
      {
          public static Func<DataContext, int, T> Get =
              CompiledQuery.Compile<DataContext, int, T>(
                  (DataContext db, int id) => (from t in A.Queries.Get(db, id)
                                               where !t.Item.Deleted 
                                               select t).SingleOrDefault());
      }

      public abstract TrackingItem Item;
}

我想要做的就是根据添加了几个约束的原始文件编译一个新查询。这不是执行两个查询

1 个答案:

答案 0 :(得分:0)

如果A.Queries.Get(...)返回IQueryable<>,则会有效,但编写代码会返回T。但是,如果您删除SingleOrDefault(),它应该可以正常工作。

更新:为了更好地衡量,此代码应该有效:

public static class Queries
{
    public static Func<DataContext, int, IQueryable<T>>Get =
        CompiledQuery.Compile<DataContext, int, IQueryable<T>>(
            (DataContext db, int i) => from t in db.GetTable<T>()
                                       where t.ID == i
                                       select t);
}

public static class BQueries
{
    public static Func<DataContext, int, IQueryable<T>> Get =
        CompiledQuery.Compile<DataContext, int, IQueryable<T>>(
            (DataContext db, int id) => from t in A.Queries.Get(db, id)
                                        where !t.Item.Deleted 
                                        select t);
}

在您调用SingleOrDefault()

之类的直接运算符之前,查询实际上不会执行
using(var db = new MyDataContext())
{
    var res = BQueries.Get(db, id);
    var entity = res.SingleOrDefault();
    // ...
}