修改 IQueryable.Include() 的表达式树以向连接添加条件

2024-02-22

基本上,我想实现一个存储库,即使通过导航属性也可以过滤所有软删除记录。所以我有一个基本实体,类似这样:

public abstract class Entity
{
    public int Id { get; set; }

    public bool IsDeleted { get; set; }

    ...
}

和一个存储库:

public class BaseStore<TEntity> : IStore<TEntity> where TEntity : Entity
{
    protected readonly ApplicationDbContext db;

    public IQueryable<TEntity> GetAll()
    {
        return db.Set<TEntity>().Where(e => !e.IsDeleted)
            .InterceptWith(new InjectConditionVisitor<Entity>(entity => !entity.IsDeleted));
    }

    public IQueryable<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate)
    {
        return GetAll().Where(predicate);
    }

    public IQueryable<TEntity> GetAllWithDeleted()
    {
        return db.Set<TEntity>();
    }

    ...
}

InterceptWith 函数来自这个项目:https://github.com/davidfowl/QueryInterceptor https://github.com/davidfowl/QueryInterceptor and https://github.com/StefH/QueryInterceptor https://github.com/StefH/QueryInterceptor(与异步实现相同)

的一个用法IStore<Project>好像:

var project = await ProjectStore.GetAll()
          .Include(p => p.Versions).SingleOrDefaultAsync(p => p.Id == projectId);

我实现了一个ExpressionVisitor:

internal class InjectConditionVisitor<T> : ExpressionVisitor
{
    private Expression<Func<T, bool>> queryCondition;

    public InjectConditionVisitor(Expression<Func<T, bool>> condition)
    {
        queryCondition = condition;
    }

    public override Expression Visit(Expression node)
    {
        return base.Visit(node);
    }
}

但这就是我陷入困境的地方。我在 Visit 函数中放置了一个断点来查看我得到了什么表达式,以及何时应该厚颜无耻地做一些事情,但它永远不会到达我的树的 Include(p => p.Versions) 部分。

我看到了一些其他可能有效的解决方案,但这些是“永久的”,例如EntityFramework.Filters https://github.com/jbogard/EntityFramework.Filters似乎适合大多数用例,但在配置 DbContext 时必须添加过滤器 - 但是,您可以禁用过滤器,但我不想为每个查询禁用并重新启用过滤器。另一个像这样的解决方案是订阅 ObjectContext 的 ObjectMaterialized 事件,但我也不喜欢它。

我的目标是“捕获”访问者中的包含内容并修改表达式树以向连接添加另一个条件,该条件仅在您使用商店的 GetAll 函数之一时检查记录的 IsDeleted 字段。任何帮助,将不胜感激!

Update

我的存储库的目的是隐藏基本实体的一些基本行为 - 它还包含“创建/最后修改日期”、“创建/最后修改日期”、时间戳等。我的 BLL 通过此存储库获取所有数据,因此它确实如此不需要担心这些,商店会处理所有的事情。也有可能继承BaseStore对于特定的类(然后我配置的 DI 将注入到继承的类中IStore<Project>如果存在),您可以在其中添加特定行为。比如你修改了一个项目,你需要添加这些修改历史,那么你只需要把这个添加到继承的store的更新功能中即可。

当您查询具有导航属性的类(因此任何类 :D )时,问题就开始了。有两个具体实体:

  public class Project : Entity 
  {
      public string Name { get; set; }

      public string Description { get; set; }

      public virtual ICollection<Platform> Platforms { get; set; }

      //note: this version is not historical data, just the versions of the project, like: 1.0.0, 1.4.2, 2.1.0, etc.
      public virtual ICollection<ProjectVersion> Versions { get; set; }
  }

  public class Platform : Entity 
  {
      public string Name { get; set; }

      public virtual ICollection<Project> Projects { get; set; }

      public virtual ICollection<TestFunction> TestFunctions { get; set; }
  }

  public class ProjectVersion : Entity 
  {
      public string Code { get; set; }

      public virtual Project Project { get; set; }
  }

因此,如果我想列出项目的版本,我会致电商店:await ProjectStore.GetAll().Include(p => p.Versions).SingleOrDefaultAsync(p => p.Id == projectId)。我不会得到已删除的项目,但如果该项目存在,它将返回与其相关的所有版本,甚至是已删除的版本。在这种特定情况下,我可以从另一侧开始并调用 ProjectVersionStore,但如果我想通过 2 个以上的导航属性进行查询,那么游戏就结束了:)

预期的行为是:如果我将版本包含到项目中,它应该只查询未删除的版本 - 因此生成的 sql 连接应该包含[Versions].[IsDeleted] = FALSE状况也。复杂的情况甚至更加复杂,例如Include(project => project.Platforms.Select(platform => platform.TestFunctions)).

我尝试这样做的原因是我不想将 BLL 中的所有 Include 重构为其他内容。这是懒惰的部分:) 另一个是我想要一个透明的解决方案,我不希望 BLL 知道所有这些。如果不是绝对必要,接口应该保持不变。我知道这只是一个扩展方法,但这种行为应该在存储层中。


您使用的 include 方法调用 QueryableExtensions.Include(source, path1) 方法,该方法将表达式转换为字符串路径。 这就是 include 方法的作用:

public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path)
{
  Check.NotNull<IQueryable<T>>(source, "source");
  Check.NotNull<Expression<Func<T, TProperty>>>(path, "path");
  string path1;
  if (!DbHelpers.TryParsePath(path.Body, out path1) || path1 == null)
    throw new ArgumentException(Strings.DbExtensions_InvalidIncludePathExpression, "path");
  return QueryableExtensions.Include<T>(source, path1);
}

因此,您的表达式如下所示(检查表达式中的“Include”或“IncludeSpan”方法):

 value(System.Data.Entity.Core.Objects.ObjectQuery`1[TEntity]).MergeAs(AppendOnly)
   .IncludeSpan(value(System.Data.Entity.Core.Objects.Span))

您应该挂接 VisitMethodCall 来添加您的表达式:

internal class InjectConditionVisitor<T> : ExpressionVisitor
{
    private Expression<Func<T, bool>> queryCondition;

    protected override Expression VisitMethodCall(MethodCallExpression node)
    {
        Expression expression = node;
        if (node.Method.Name == "Include" || node.Method.Name == "IncludeSpan")
        {
            // DO something here! Let just add an OrderBy for fun

            // LAMBDA: x => x.[PropertyName]
            var parameter = Expression.Parameter(typeof(T), "x");
            Expression property = Expression.Property(parameter, "ColumnInt");
            var lambda = Expression.Lambda(property, parameter);

            // EXPRESSION: expression.[OrderMethod](x => x.[PropertyName])
            var orderByMethod = typeof(Queryable).GetMethods().First(x => x.Name == "OrderBy" && x.GetParameters().Length == 2);
            var orderByMethodGeneric = orderByMethod.MakeGenericMethod(typeof(T), property.Type);
            expression = Expression.Call(null, orderByMethodGeneric, new[] { expression, Expression.Quote(lambda) });
        }
        else
        {
            expression = base.VisitMethodCall(node);
        }

        return expression;
    }
}

David Fowl 的 QueryInterceptor 项目不支持“包含”。实体框架尝试使用反射查找“包含”方法,如果未找到则返回当前查询(就是这种情况)。

免责声明: 我是该项目的所有者EF+ http://entityframework-plus.net/.

我添加了一个 QueryInterceptor 功能,支持“包含”来回答您的问题。由于尚未添加单元测试,该功能尚不可用,但您可以下载并尝试源代码:查询拦截器源码 https://github.com/zzzprojects/EntityFramework-Plus/tree/master/src/Z.EntityFramework.Plus.EF6/QueryInterceptor

如果您有问题,请直接联系我(在我的 GitHub 主页底部发送电子邮件),否则这将开始偏离主题。

请注意,“包含”方法通过隐藏一些先前的表达式来修改表达式。因此,有时很难理解幕后到底发生了什么。

我的项目还包含查询过滤器功能,我认为它具有更大的灵活性。


EDIT:从更新的必需中添加工作示例

这是您可以根据您的要求使用的起始代码:

public IQueryable<TEntity> GetAll()
{
    var conditionVisitor = new InjectConditionVisitor<TEntity>("Versions", db.Set<TEntity>.Provider, x => x.Where(y => !y.IsDeleted));
    return db.Set<TEntity>().Where(e => !e.IsDeleted).InterceptWith(conditionVisitor);
}

var project = await ProjectStore.GetAll().Include(p => p.Versions).SingleOrDefaultAsync(p => p.Id == projectId);

internal class InjectConditionVisitor<T> : ExpressionVisitor
{
    private readonly string NavigationString;
    private readonly IQueryProvider Provider;
    private readonly Func<IQueryable<T>, IQueryable<T>> QueryCondition;

    public InjectConditionVisitor(string navigationString, IQueryProvider provder , Func<IQueryable<T>, IQueryable<T>> queryCondition)
    {
        NavigationString = navigationString;
        Provider = provder;
        QueryCondition = queryCondition;
    }

    protected override Expression VisitMethodCall(MethodCallExpression node)
    {
        Expression expression = node;

        bool isIncludeSpanValid = false;

        if (node.Method.Name == "IncludeSpan")
        {
            var spanValue = (node.Arguments[0] as ConstantExpression).Value;

            // The System.Data.Entity.Core.Objects.Span class and SpanList is internal, let play with reflection!
            var spanListProperty = spanValue.GetType().GetProperty("SpanList", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            var spanList = (IEnumerable)spanListProperty.GetValue(spanValue);

            foreach (var span in spanList)
            {
                var spanNavigationsField = span.GetType().GetField("Navigations", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                var spanNavigation = (List<string>)spanNavigationsField.GetValue(span);

                if (spanNavigation.Contains(NavigationString))
                {
                    isIncludeSpanValid = true;
                    break;
                }
            }
        }

        if ((node.Method.Name == "Include" && (node.Arguments[0] as ConstantExpression).Value.ToString() == NavigationString)
            || isIncludeSpanValid)
        {

            // CREATE a query from current expression
            var query = Provider.CreateQuery<T>(expression);

            // APPLY the query condition
            query = QueryCondition(query);

            // CHANGE the query expression
            expression = query.Expression;
        }
        else
        {
            expression = base.VisitMethodCall(node);
        }

        return expression;
    }
}

EDIT:回答子问题

Include 和 IncludeSpan 之间的区别

据我了解

IncludeSpan:当原始查询尚未通过 LINQ 方法修改时出现。

Include:当原始查询已被 LINQ 方法修改时出现(您不再看到以前的表达式)

-- Expression: {value(System.Data.Entity.Core.Objects.ObjectQuery`1[Z.Test.EntityFramework.Plus.Association_Multi_OneToMany_Left]).MergeAs(AppendOnly).IncludeSpan(value(System.Data.Entity.Core.Objects.Span))}
var q = ctx.Association_Multi_OneToMany_Lefts.Include(x => x.Right1s).Include(x => x.Right2s);


-- Expression: {value(System.Data.Entity.Core.Objects.ObjectQuery`1[Z.Test.EntityFramework.Plus.Association_Multi_OneToMany_Left]).Include("Right2s")}
var q = ctx.Association_Multi_OneToMany_Lefts.Include(x => x.Right1s).Where(x => x.ColumnInt > 10).Include(x => x.Right2s);

如何包含和过滤相关实体

包含不允许您过滤相关实体。您可以在这篇文章中找到 2 个解决方案:EF。如何在模型中仅包含一些子结果? https://stackoverflow.com/questions/34963319/ef-how-to-include-only-some-sub-results-in-a-model/34971161#34971161

  • 一种涉及使用投影
  • 其中之一涉及使用我的库中的 EF+ Query IncludeFilter
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

修改 IQueryable.Include() 的表达式树以向连接添加条件 的相关文章

  • 为什么pow函数比简单运算慢?

    从我的一个朋友那里 我听说 pow 函数比简单地将底数乘以它的指数的等价函数要慢 例如 据他介绍 include
  • IdentityServer 4 对它的工作原理感到困惑

    我阅读和观看了很多有关 Identity Server 4 的内容 但我仍然对它有点困惑 因为似乎有很多移动部件 我现在明白这是一个单独的项目 它处理用户身份验证 我仍然不明白的是用户如何注册它 谁存储用户名 密码 我打算进行此设置 Rea
  • 查找进程的完整路径

    我已经编写了 C 控制台应用程序 当我启动应用程序时 不使用cmd 我可以看到它列在任务管理器的进程列表中 现在我需要编写另一个应用程序 在其中我需要查找以前的应用程序是否正在运行 我知道应用程序名称和路径 所以我已将管理对象搜索器查询写入
  • 为什么在 WebApi 上下文中在 using 块中使用 HttpClient 是错误的?

    那么 问题是为什么在 using 块中使用 HttpClient 是错误的 但在 WebApi 上下文中呢 我一直在读这篇文章不要阻止异步代码 https blog stephencleary com 2012 07 dont block
  • 从客户端访问 DomainService 中的自定义对象

    我正在使用域服务从 Silverlight 客户端的数据库中获取数据 在DomainService1 cs中 我添加了以下内容 EnableClientAccess public class Product public int produ
  • 对 std::vector 进行排序但忽略某个数字

    我有一个std vector
  • 使用 LINQ to SQL 时避免连接超时的最佳实践

    我需要知道在 net 应用程序中使用 LINQ to SQL 时避免连接超时的最佳实践 特别是在返回时IQueryable
  • C# 存档中的文件列表

    我正在创建一个 FileFinder 类 您可以在其中进行如下搜索 var fileFinder new FileFinder new string C MyFolder1 C MyFolder2 new string
  • 识别 Visual Studio 中的重载运算符 (c++)

    有没有办法使用 Visual Studio 快速直观地识别 C 中的重载运算符 在我看来 C 中的一大问题是不知道您正在使用的运算符是否已重载 Visual Studio 或某些第三方工具中是否有某些功能可以自动突出显示重载运算符或对重载运
  • 在视口中查找 WPF 控件

    Updated 这可能是一个简单或复杂的问题 但在 wpf 中 我有一个列表框 我用一个填充数据模板从列表中 有没有办法找出特定的数据模板项位于视口中 即我已滚动到其位置并且可以查看 目前我连接到了 listbox ScrollChange
  • 如何在 C 中安全地声明 16 位字符串文字?

    我知道已经有一个标准方法 前缀为L wchar t test literal L Test 问题是wchar t不保证是16位 但是对于我的项目 我需要16位wchar t 我还想避免通过的要求 fshort wchar 那么 C 不是 C
  • 为什么这个二维指针表示法有效,而另一个则无效[重复]

    这个问题在这里已经有答案了 这里我编写了一段代码来打印 3x3 矩阵的对角线值之和 这里我必须将矩阵传递给函数 矩阵被传递给指针数组 代码可以工作 但问题是我必须编写参数的方式如下 int mat 3 以下导致程序崩溃 int mat 3
  • 保护 APK 中的字符串

    我正在使用 Xamarin 的 Mono for Android 开发一个 Android 应用程序 我目前正在努力使用 Google Play API 添加应用内购买功能 为此 我需要从我的应用程序内向 Google 发送公共许可证密钥
  • 元数据集合中不存在标识为“ ”的成员。\r\n参数名称: Identity

    我在尝试调试时稍微简化了代码 HttpPost public ActionResult Register User model DateTime bla new DateTime 2012 12 12 try User user new U
  • C++ 中的双精度型数字

    尽管内部表示有 17 位 但 IEE754 64 位 浮点应该正确表示 15 位有效数字 有没有办法强制第 16 位和第 17 位为零 Ref http msdn microsoft com en us library system dou
  • 等待 IAsyncResult 函数直至完成

    我需要创建等待 IAsyncResult 方法完成的机制 我怎样才能做到这一点 IAsyncResult result contactGroupServices BeginDeleteContact contactToRemove Uri
  • WPF DataGridTemplateColumn 组合框更新所有行

    我有这个 XAML 它从 ItemSource 是枚举的组合框中选择一个值 我使用的教程是 http www c sharpcorner com uploadfile dpatra combobox in datagrid in wpf h
  • Unity:通过拦截将两个接口注册为一个单例

    我有一个实现两个接口的类 我想对该类的方法应用拦截 我正在遵循中的建议Unity 将两个接口注册为一个单例 https stackoverflow com questions 1394650 unity register two inter
  • 将数组作为参数传递

    如果我们修改作为方法内参数传递的数组的内容 则修改是在参数的副本而不是原始参数上完成的 因此结果不可见 当我们调用具有引用类型参数的方法时 会发生什么过程 这是我想问的代码示例 using System namespace Value Re
  • 不区分大小写的字符串比较 C++ [重复]

    这个问题在这里已经有答案了 我知道有一些方法可以进行忽略大小写的比较 其中涉及遍历字符串或一个good one https stackoverflow com questions 11635 case insensitive string

随机推荐