”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Linq、Criteria API 和 Query Over 扩展 NHibernate 的 Ardalis.Specification

使用 Linq、Criteria API 和 Query Over 扩展 NHibernate 的 Ardalis.Specification

发布于2024-11-07
浏览:685

Extending Ardalis.Specification for NHibernate with Linq, Criteria API, and Query Over

Ardalis.Specification is a powerful library that enables the specification pattern for querying databases, primarily designed for Entity Framework Core, but here I'll demonstrate how you can extend Ardalis.Specification to use NHibernate as an ORM as well.

This blog post assumes you have some experience with Ardalis.Specification, and want to use it in a project using NHibernate. If you are not familiar with Ardalis.Specification yet, head over to the documentation to learn more.

First, in NHibernate there are three different built-in ways to perform queries

  • Linq to query (using IQueryable)
  • Criteria API
  • Query Over

I'll go through how you can extend Ardalis.Specification to handle all 3 ways, but since Linq to Query also works with IQueryable like Entity Framework Core, I'll go through that option first.

Linq to query

There is a small nuance between Entity Framework Core and NHIbernate when it comes to create join relationships. In Entity Framework Core we have extensions methods on IQueryable: Include and ThenInclude (these are also the method names used in Ardalis.Specification).

Fetch, FetchMany, ThenFetch and ThenFetchMany are NHibernate specific methods on IQueryable that do joins. The IEvaluator gives us the extensibility we need to invoke the correct extension method when we work with NHibernate.

Add an implementation of IEvaluator as follows:

public class FetchEvaluator : IEvaluator
{
   private static readonly MethodInfo FetchMethodInfo = typeof(EagerFetchingExtensionMethods)
        .GetTypeInfo().GetDeclaredMethods(nameof(EagerFetchingExtensionMethods.Fetch))
        .Single();

   private static readonly MethodInfo FetchManyMethodInfo = typeof(EagerFetchingExtensionMethods)
       .GetTypeInfo().GetDeclaredMethods(nameof(EagerFetchingExtensionMethods.FetchMany))
       .Single();

   private static readonly MethodInfo ThenFetchMethodInfo
       = typeof(EagerFetchingExtensionMethods)
           .GetTypeInfo().GetDeclaredMethods(nameof(EagerFetchingExtensionMethods.ThenFetch))
           .Single();

   private static readonly MethodInfo ThenFetchManyMethodInfo
       = typeof(EagerFetchingExtensionMethods)
           .GetTypeInfo().GetDeclaredMethods(nameof(EagerFetchingExtensionMethods.ThenFetchMany))
           .Single();

    public static FetchEvaluator Instance { get; } = new FetchEvaluator();

    public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class
    {
        foreach (var includeInfo in specification.IncludeExpressions)
        {
            query = includeInfo.Type switch
            {
                IncludeTypeEnum.Include => BuildInclude(query, includeInfo),
                IncludeTypeEnum.ThenInclude => BuildThenInclude(query, includeInfo),
                _ => query
            };
        }

        return query;
    }

    public bool IsCriteriaEvaluator { get; } = false;

    private IQueryable BuildInclude(IQueryable query, IncludeExpressionInfo includeInfo)
    {
        _ = includeInfo ?? throw new ArgumentNullException(nameof(includeInfo));

        var methodInfo = (IsGenericEnumerable(includeInfo.PropertyType, out var propertyType)
            ? FetchManyMethodInfo 
            : FetchMethodInfo);

       var method = methodInfo.MakeGenericMethod(includeInfo.EntityType, propertyType);

       var result = method.Invoke(null, new object[] { query, includeInfo.LambdaExpression });
        _ = result ?? throw new TargetException();

        return (IQueryable)result;
    }

    private IQueryable BuildThenInclude(IQueryable query, IncludeExpressionInfo includeInfo)
    {
        _ = includeInfo ?? throw new ArgumentNullException(nameof(includeInfo));
        _ = includeInfo.PreviousPropertyType ?? throw new ArgumentNullException(nameof(includeInfo.PreviousPropertyType));

        var method = (IsGenericEnumerable(includeInfo.PreviousPropertyType, out var previousPropertyType)
            ? ThenFetchManyMethodInfo
            : ThenFetchMethodInfo);

        IsGenericEnumerable(includeInfo.PropertyType, out var propertyType);

        var result = method.MakeGenericMethod(includeInfo.EntityType, previousPropertyType, propertyType)
            .Invoke(null, new object[] { query, includeInfo.LambdaExpression });

        _ = result ?? throw new TargetException();

        return (IQueryable)result;
    }

    private static bool IsGenericEnumerable(Type type, out Type propertyType)
    {
        if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IEnumerable)))
        {
            propertyType = type.GenericTypeArguments[0];

            return true;
        }

        propertyType = type;

        return false;
    }
}

Next we need to configure ISpecificationEvaluator to use our FetchEvaluator (and other evaluators). We add an implementation ISpecificationEvaluator as follows with the Evaluators configured in the constructor. WhereEvaluator, OrderEvaluator and PaginationEvaluator are all in the Ardalis.Specification and works well NHibernate as well.

public class LinqToQuerySpecificationEvaluator : ISpecificationEvaluator
{
    private List Evaluators { get; } = new List();

    public LinqToQuerySpecificationEvaluator()
    {
        Evaluators.AddRange(new IEvaluator[]
        {
            WhereEvaluator.Instance,
            OrderEvaluator.Instance,
            PaginationEvaluator.Instance,
            FetchEvaluator.Instance
        });
    }


    public IQueryable GetQuery(IQueryable query, ISpecification specification) where T : class
    {
        if (specification is null) throw new ArgumentNullException(nameof(specification));
        if (specification.Selector is null && specification.SelectorMany is null) throw new SelectorNotFoundException();
        if (specification.Selector is not null && specification.SelectorMany is not null) throw new ConcurrentSelectorsException();

        query = GetQuery(query, (ISpecification)specification);

        return specification.Selector is not null
            ? query.Select(specification.Selector)
            : query.SelectMany(specification.SelectorMany!);
    }

    public IQueryable GetQuery(IQueryable query, ISpecification specification, bool evaluateCriteriaOnly = false) where T : class
    {
        if (specification is null) throw new ArgumentNullException(nameof(specification));

        var evaluators = evaluateCriteriaOnly ? Evaluators.Where(x => x.IsCriteriaEvaluator) : Evaluators;

        foreach (var evaluator in evaluators)
           query = evaluator.GetQuery(query, specification);

        return query;
    }
}

Now we can create a reference to LinqToQuerySpecificationEvaluator in our repository that may look something like this:

public class Repository : IRepository
{
    private readonly ISession _session;
    private readonly ISpecificationEvaluator _specificationEvaluator;

    public Repository(ISession session)
    {
        _session = session;
        _specificationEvaluator = new LinqToQuerySpecificationEvaluator();
    } 

    ... other repository methods

    public IEnumerable List(ISpecification specification) where T : class
    {
        return _specificationEvaluator.GetQuery(_session.Query().AsQueryable(), specification).ToList();
    }

    public IEnumerable List(ISpecification specification) where T : class
    {    
        return _specificationEvaluator.GetQuery(_session.Query().AsQueryable(), specification).ToList();
    }

    public void Dispose()
    {
        _session.Dispose();
    }
}

That's it. We can now use Linq to Query in our specifications just like we normally do with Ardalis.Specification:

public class TrackByName : Specification
{
    public TrackByName(string trackName)
    {
        Query.Where(x => x.Name == trackName);
    }
}

Now that we've covered Linq-based queries, let's move on to handling Criteria API and Query Over, which require a different approach.

Mixing Linq, Criteria, and Query Over in NHibernate

Since Criteria API and Query Over has their own implementation to generate SQL, and doesn't use IQueryable, they are incompatible with the IEvaluator interface. My solution is to avoid using the IEvaluator interface for these methods in this case, but rather focus on the benefits of the specification pattern. But I also want to be able to mix
Linq to Query, Criteria and Query Over with in my solution (if you only need one of these implementations, you can cherry-pick for your best needs).

To be able to do that, I add four new classes that inherits Specification or Specification

NOTE: The assembly where you define these classes needs a reference to NHibernate as we define actions for Criteria and a QueryOver, that can be found in NHibernate

public class CriteriaSpecification : Specification
{
    private Action? _action;
    public Action GetCriteria() => _action ?? throw new NotSupportedException("The criteria has not been specified. Please use UseCriteria() to define the criteria.");
    protected void UseCriteria(Action action) => _action = action;
}

public class CriteriaSpecification : Specification
{
    private Action? _action;
    public Action GetCriteria() => _action ?? throw new NotSupportedException("The criteria has not been specified. Please use UseCriteria() to define the criteria.");
    protected void UseCriteria(Action action) => _action = action;
}

public class QueryOverSpecification : Specification
{
    private Action>? _action;
    public Action> GetQueryOver() => _action ?? throw new NotSupportedException("The Query over has not been specified. Please use the UseQueryOver() to define the query over.");
    protected void UseQueryOver(Action> action) => _action = action;
}

public class QueryOverSpecification : Specification
{
    private Func, IQueryOver>? _action;
    public Func, IQueryOver> GetQueryOver() => _action ??  throw new NotSupportedException("The Query over has not been specified. Please use the UseQueryOver() to define the query over.");
    protected void UseQueryOver(Func, IQueryOver> action) => _action = action;
}

Then we can use pattern matching in our repository to change how we do queries with NHibernate

public IEnumerable List(ISpecification specification) where T : class
{
    return specification switch
    {
        CriteriaSpecification criteriaSpecification => 
            _session.CreateCriteria()
                .Apply(query => criteriaSpecification.GetCriteria().Invoke(query))
                .List(),

        QueryOverSpecification queryOverSpecification => 
            _session.QueryOver()
                .Apply(queryOver => queryOverSpecification.GetQueryOver().Invoke(queryOver))
                .List(),

        _ => _specificationEvaluator.GetQuery(_session.Query().AsQueryable(), specification).ToList()
    };
}

public IEnumerable List(ISpecification specification) where T : class
{

    return specification switch
    {
        CriteriaSpecification criteriaSpecification => 
            _session.CreateCriteria()
                .Apply(query => criteriaSpecification.GetCriteria().Invoke(query))
                .List(),

        QueryOverSpecification queryOverSpecification =>
            _session.QueryOver()
                .Apply(queryOver => queryOverSpecification.GetQueryOver().Invoke(queryOver))
                .List(),

        _ => _specificationEvaluator.GetQuery(_session.Query().AsQueryable(), specification).ToList()
    };
}

The Apply() method above are an extension method that simplifies the query to a single line:

public static class QueryExtensions
{
    public static T Apply(this T obj, Action action)
    {
        action(obj);
        return obj;
    }

    public static TResult Apply(this T obj, Func func)
    {
        return func(obj);
    }
}

Criteria specification example

NOTE: The assembly where you define these classes needs a reference to NHibernate as we define actions for Criteria, that can be found in NHibernate

public class TrackByNameCriteria : CriteriaSpecification
{
    public TrackByNameCriteria(string trackName)
    {
        this.UseCriteria(criteria => criteria.Add(Restrictions.Eq(nameof(Track.Name), trackName)));
    }
}

Query over specification example

NOTE: The assembly where you define these classes needs a reference to NHibernate as we define actions for a QueryOver, that can be found in NHibernate

public class TrackByNameQueryOver : QueryOverSpecification
{
    public TrackByNameQueryOver(string trackName)
    {
        this.UseQueryOver(queryOver => queryOver.Where(x => x.Name == trackName));
    }
}

By extending Ardalis.Specification for NHibernate, we unlock the ability to use Linq to Query, Criteria API, and Query Over—all within a single repository pattern. This approach offers a highly adaptable and powerful solution for NHibernate users

版本声明 本文转载于:https://dev.to/greenfieldcoder/extending-ardalisspecification-for-nhibernate-with-linq-criteria-api-and-query-over-24pn如有侵犯,请联系[email protected]删除
最新教程 更多>
  • Floyd 算法如何检测链表中的循环?
    Floyd 算法如何检测链表中的循环?
    使用 Floyd 算法检测链表中的循环确定给定链表是否包含循环在 Java 编程中是一项具有挑战性的任务。当列表中的最后一个节点引用前一个节点而不是空引用时,就会发生循环。为了有效地检测循环,开发人员通常采用 Floyd 的循环查找算法,也称为龟兔赛跑算法。该算法使用两个引用,一个慢速引用和一个快速...
    编程 发布于2024-11-07
  • 如何在不使用 Flash 的情况下使用 JavaScript 在客户端调整图像大小?
    如何在不使用 Flash 的情况下使用 JavaScript 在客户端调整图像大小?
    使用 JavaScript 在客户端调整图像大小:开源解决方案在当今的 Web 开发环境中,通常需要在客户端调整图像大小之前将它们上传到服务器。这种方法可以优化图像质量,减少服务器负载,并通过加快页面加载时间来改善用户体验。虽然 Flash 是调整图像大小的常见选项,但许多开发人员宁愿避免使用它。幸...
    编程 发布于2024-11-07
  • 通信:数据获取模式
    通信:数据获取模式
    重大公告! 我开始了我日常的前端系统设计学习之旅。我将在博客中分享每个模块的见解。所以,这就是开始,还有更多精彩! 在本博客中,我们将探讨前端系统设计所必需的不同数据获取机制,包括短轮询、长轮询、WebSocket、服务器发送事件 (SSE) 和 Webhooks。每种技术都满足向客户端和服务器传输...
    编程 发布于2024-11-07
  • #daysofMiva 编码挑战日:将 JavaScript 链接到 HTML 文件。
    #daysofMiva 编码挑战日:将 JavaScript 链接到 HTML 文件。
    嗨,大家好。很抱歉这篇文章迟发了,但迟发总比不发好?无论如何,让我们深入了解今天的文章。 为什么将 Javascript 链接到 HTML 文件。 JavaScript 是一种在浏览器中运行的编程语言,可以操纵网页的内容、结构和样式。通过将 JavaScript 文件链接到 HTML...
    编程 发布于2024-11-07
  • 为什么我的 canvas.toDataURL() 没有保存我的图像?
    为什么我的 canvas.toDataURL() 没有保存我的图像?
    Resolving Image Saving Issues with canvas.toDataURL()When attempting to utilize canvas.toDataURL() to save a canvas as an image, you may encounter dif...
    编程 发布于2024-11-07
  • Node.js 中的新增功能
    Node.js 中的新增功能
    TL;DR: 让我们探索 Node.js 22 的主要功能,包括 ECMAScript 模块支持和 V8 引擎更新。此版本引入了 Maglev 编译器和内置 WebSocket 客户端,以增强性能和实时通信。还涵盖了测试、调试和文件系统管理方面的改进。 Node.js 22 将于 10 月进入 LT...
    编程 发布于2024-11-07
  • 了解 MongoDB 的distinct() 操作:实用指南
    了解 MongoDB 的distinct() 操作:实用指南
    MongoDB 的distinct() 操作是一个强大的工具,用于从集合中的指定字段检索唯一值。本指南将帮助您了解distinct() 的用途、使用它的原因和时间,以及如何在 MongoDB 查询中有效地实现它。 什么是distinct()? distinct() 方法返回集合或集合...
    编程 发布于2024-11-07
  • 为什么 JavaScript 中的“0”在比较中为 False,而在“if”语句中为 True?
    为什么 JavaScript 中的“0”在比较中为 False,而在“if”语句中为 True?
    揭开 JavaScript 的悖论:为什么“0”在比较中为假,但在 If 语句中为假在 JavaScript 中,原语 " 的行为0”给开发者带来了困惑。虽然诸如“==”之类的逻辑运算符将“0”等同于假,但“0”在“if”条件下表现为真。比较悖论代码下面演示了比较悖论:"0&qu...
    编程 发布于2024-11-07
  • GitHub Copilot 有其怪癖
    GitHub Copilot 有其怪癖
    过去 4 个月我一直在将 GitHub Copilot 与我们的生产代码库一起使用,以下是我的一些想法: 好的: 解释复杂代码:它非常适合分解棘手的代码片段或业务逻辑并正确解释它们。 单元测试:非常擅长编写单元测试并快速生成多个基于场景的测试用例。 代码片段:它可以轻松地为通用用例生成有用的代码片段...
    编程 发布于2024-11-07
  • 静态类或实例化类:什么时候应该选择哪个?
    静态类或实例化类:什么时候应该选择哪个?
    在静态类和实例化类之间做出选择:概述在 PHP 中设计软件应用程序时,开发人员经常面临在使用静态类或实例化对象。这个决定可能会对程序的结构、性能和可测试性产生重大影响。何时使用静态类静态类适用于对象不具备静态类的场景独特的数据,只需要访问共享功能。例如,用于将 BB 代码转换为 HTML 的实用程序...
    编程 发布于2024-11-07
  • ⚠️ 在 JavaScript 中使用 `var` 的隐藏危险:为什么是时候继续前进了
    ⚠️ 在 JavaScript 中使用 `var` 的隐藏危险:为什么是时候继续前进了
    关键字 var 多年来一直是 JavaScript 中声明变量的默认方式。但是,它有一些怪癖和陷阱,可能会导致代码出现意外行为。现代替代方案(如 let 和 const)解决了许多此类问题,使它们成为大多数情况下声明变量的首选。 1️⃣ 提升:var 在不知不觉中声明变量! ?解释:...
    编程 发布于2024-11-07
  • PDO::MYSQL_ATTR_INIT_COMMAND 需要“SET CHARACTER SET utf8”吗?
    PDO::MYSQL_ATTR_INIT_COMMAND 需要“SET CHARACTER SET utf8”吗?
    在带有“PDO::MYSQL_ATTR_INIT_COMMAND”的 PDO 中“SET CHARACTER SET utf8”是否必要?在 PHP 和 MySQL 中,“SET NAMES” utf8”和“SET CHARACTER SET utf8”通常在使用 UTF-8 编码时使用。但是,当使...
    编程 发布于2024-11-07
  • 为什么使用Password_Hash函数时哈希值会变化?
    为什么使用Password_Hash函数时哈希值会变化?
    了解Password_Hash函数中不同的哈希值在开发安全认证系统时,开发人员经常会遇到使用password_hash获取不同密码哈希值的困惑功能。为了阐明此行为并确保正确的密码验证,让我们分析此函数背后的机制。密码加盐:有意的功能password_hash 函数有意生成唯一的盐它对每个密码进行哈希...
    编程 发布于2024-11-07
  • 为什么与谷歌竞争并不疯狂
    为什么与谷歌竞争并不疯狂
    大家好,我是 Antonio,Litlyx 的首席执行官,我们的对手是一些巨头! Microsoft Clarity、Google Analytics、MixPanel...它们是分析领域的重要参与者。当人们听说一家初创公司正在与如此知名的公司合作时,他们常常会感到惊讶。但让我们看看为什么与谷歌这样...
    编程 发布于2024-11-07
  • 如何在 Java Streams 中高效地将对象列表转换为可选对象?
    如何在 Java Streams 中高效地将对象列表转换为可选对象?
    使用 Java 8 的可选和 Stream::flatMap 变得简洁使用 Java 8 流时,将 List 转换为可选 并有效地提取第一个 Other 值可能是一个挑战。虽然 flatMap 通常需要返回流,但可选的 Stream() 的缺失使问题变得复杂。Java 16 解决方案Java 16 ...
    编程 发布于2024-11-07

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3