Ardalis.Specification 是一个功能强大的库,支持查询数据库的规范模式,主要为 Entity Framework Core 设计,但在这里我将演示如何扩展 Ardalis.Specification 来使用NHibernate 也是一种 ORM。
这篇博文假设您对 Ardalis.Specification 有一定的经验,并且希望在使用 NHibernate 的项目中使用它。如果您还不熟悉 Ardalis.Specification,请参阅文档以了解更多信息。
首先,NHibernate 中有三种不同的内置方法来执行查询
- Linq 查询(使用 IQueryable)
- 标准 API
- 查询结束
我将介绍如何扩展 Ardalis.Specification 来处理所有 3 种方式,但由于 Linq to Query 也可以像 Entity Framework Core 一样与 IQueryable 配合使用,因此我将首先介绍该选项。
Linq 查询
在创建连接关系时,Entity Framework Core 和 NHIbernate 之间存在细微差别。在 Entity Framework Core 中,我们在 IQueryable 上有扩展方法: Include 和 ThenInclude (这些也是 Ardalis.Specification 中使用的方法名称)。
Fetch、FetchMany、ThenFetch 和 ThenFetchMany 是 IQueryable 上执行连接的 NHibernate 特定方法。 IEvaluator 为我们提供了使用 NHibernate 时调用正确扩展方法所需的可扩展性。
添加 IEvaluator 的实现,如下所示:
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<t> GetQuery<t>(IQueryable<t> query, ISpecification<t> specification) where T : class { foreach (var includeInfo in specification.IncludeExpressions) { query = includeInfo.Type switch { IncludeTypeEnum.Include => BuildInclude<t>(query, includeInfo), IncludeTypeEnum.ThenInclude => BuildThenInclude<t>(query, includeInfo), _ => query }; } return query; } public bool IsCriteriaEvaluator { get; } = false; private IQueryable<t> BuildInclude<t>(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<t>)result; } private IQueryable<t> BuildThenInclude<t>(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<t>)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; } } </t></t></t></t></t></t></t></t></t></t></t></t>
接下来我们需要配置 ISpecificationEvaluator 以使用我们的 FetchEvaluator(和其他评估器)。我们添加一个实现 ISpecificationEvaluator ,如下所示,并在构造函数中配置评估器。 WhereEvaluator、OrderEvaluator 和 PaginationEvaluator 都在 Ardalis.Specification 中,并且在 NHibernate 中也能很好地工作。
public class LinqToQuerySpecificationEvaluator : ISpecificationEvaluator { private List<ievaluator> Evaluators { get; } = new List<ievaluator>(); public LinqToQuerySpecificationEvaluator() { Evaluators.AddRange(new IEvaluator[] { WhereEvaluator.Instance, OrderEvaluator.Instance, PaginationEvaluator.Instance, FetchEvaluator.Instance }); } public IQueryable<tresult> GetQuery<t tresult>(IQueryable<t> query, ISpecification<t tresult> 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<t>)specification); return specification.Selector is not null ? query.Select(specification.Selector) : query.SelectMany(specification.SelectorMany!); } public IQueryable<t> GetQuery<t>(IQueryable<t> query, ISpecification<t> 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; } } </t></t></t></t></t></t></t></t></tresult></ievaluator></ievaluator>
现在我们可以在我们的存储库中创建对 LinqToQuerySpecificationEvaluator 的引用,可能如下所示:
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<t> List<t>(ISpecification<t> specification) where T : class { return _specificationEvaluator.GetQuery(_session.Query<t>().AsQueryable(), specification).ToList(); } public IEnumerable<tresult> List<t tresult>(ISpecification<t tresult> specification) where T : class { return _specificationEvaluator.GetQuery(_session.Query<t>().AsQueryable(), specification).ToList(); } public void Dispose() { _session.Dispose(); } } </t></t></t></tresult></t></t></t></t>
就是这样。现在,我们可以在规范中使用 Linq to Query,就像我们通常使用 Ardalis 一样。规范:
public class TrackByName : Specification<core.entitites.track> { public TrackByName(string trackName) { Query.Where(x => x.Name == trackName); } } </core.entitites.track>
现在我们已经介绍了基于 Linq 的查询,让我们继续处理 Criteria API 和 Query Over,这需要不同的方法。
在 NHibernate 中混合 Linq、Criteria 和 Query Over
由于 Criteria API 和 Query Over 有自己的实现来生成 SQL,并且不使用 IQueryable,因此它们与 IEvaluator 接口不兼容。我的解决方案是在这种情况下避免对这些方法使用 IEvaluator 接口,而是关注规范模式的好处。但我也希望能够混搭
我的解决方案中包含 Linq to Query、Criteria 和 Query Over(如果您只需要其中一种实现,您可以根据您的最佳需求进行挑选)。
为了能够做到这一点,我添加了四个继承Specification或Specification的新类
注意: 定义这些类的程序集需要对 NHibernate 的引用,因为我们为 Criteria 和 QueryOver 定义操作,这可以在 NHibernate
中找到
public class CriteriaSpecification<t> : Specification<t> { private Action<icriteria>? _action; public Action<icriteria> GetCriteria() => _action ?? throw new NotSupportedException("The criteria has not been specified. Please use UseCriteria() to define the criteria."); protected void UseCriteria(Action<icriteria> action) => _action = action; } public class CriteriaSpecification<t tresult> : Specification<t tresult> { private Action<icriteria>? _action; public Action<icriteria> GetCriteria() => _action ?? throw new NotSupportedException("The criteria has not been specified. Please use UseCriteria() to define the criteria."); protected void UseCriteria(Action<icriteria> action) => _action = action; } public class QueryOverSpecification<t> : Specification<t> { private Action<iqueryover t>>? _action; public Action<iqueryover t>> 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<iqueryover t>> action) => _action = action; } public class QueryOverSpecification<t tresult> : Specification<t tresult> { private Func<iqueryover t>, IQueryOver<t t>>? _action; public Func<iqueryover t>, IQueryOver<t t>> 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 t>, IQueryOver<t t>> action) => _action = action; } </t></iqueryover></t></iqueryover></t></iqueryover></t></t></iqueryover></iqueryover></iqueryover></t></t></icriteria></icriteria></icriteria></t></t></icriteria></icriteria></icriteria></t></t>
然后我们可以在存储库中使用模式匹配来更改使用 NHibernate 进行查询的方式
public IEnumerable<t> List<t>(ISpecification<t> specification) where T : class { return specification switch { CriteriaSpecification<t> criteriaSpecification => _session.CreateCriteria<t>() .Apply(query => criteriaSpecification.GetCriteria().Invoke(query)) .List<t>(), QueryOverSpecification<t> queryOverSpecification => _session.QueryOver<t>() .Apply(queryOver => queryOverSpecification.GetQueryOver().Invoke(queryOver)) .List<t>(), _ => _specificationEvaluator.GetQuery(_session.Query<t>().AsQueryable(), specification).ToList() }; } public IEnumerable<tresult> List<t tresult>(ISpecification<t tresult> specification) where T : class { return specification switch { CriteriaSpecification<t tresult> criteriaSpecification => _session.CreateCriteria<t>() .Apply(query => criteriaSpecification.GetCriteria().Invoke(query)) .List<tresult>(), QueryOverSpecification<t tresult> queryOverSpecification => _session.QueryOver<t>() .Apply(queryOver => queryOverSpecification.GetQueryOver().Invoke(queryOver)) .List<tresult>(), _ => _specificationEvaluator.GetQuery(_session.Query<t>().AsQueryable(), specification).ToList() }; } </t></tresult></t></t></tresult></t></t></t></t></tresult></t></t></t></t></t></t></t></t></t></t>
上面的Apply()方法是一个扩展方法,它将查询简化为一行:
public static class QueryExtensions { public static T Apply<t>(this T obj, Action<t> action) { action(obj); return obj; } public static TResult Apply<t tresult>(this T obj, Func<t tresult> func) { return func(obj); } } </t></t></t></t>
标准规范示例
注意: 定义这些类的程序集需要对 NHibernate 的引用,因为我们定义 Criteria 的操作,可以在 NHibernate
中找到
public class TrackByNameCriteria : CriteriaSpecification<track> { public TrackByNameCriteria(string trackName) { this.UseCriteria(criteria => criteria.Add(Restrictions.Eq(nameof(Track.Name), trackName))); } } </track>
查询超规格示例
注意: 定义这些类的程序集需要对 NHibernate 的引用,因为我们定义 QueryOver 的操作,可以在 NHibernate
中找到
public class TrackByNameQueryOver : QueryOverSpecification<track> { public TrackByNameQueryOver(string trackName) { this.UseQueryOver(queryOver => queryOver.Where(x => x.Name == trackName)); } } </track>
通过扩展 NHibernate 的 Ardalis.Specification,我们解锁了在单个存储库模式中使用 Linq to Query、Criteria API 和 Query Over 的能力。这种方法为 NHibernate 用户提供了高度适应性和强大的解决方案
以上是使用 Linq、Criteria API 和 Query Over 扩展 NHibernate 的 Ardalis.Specification的详细内容。更多信息请关注PHP中文网其他相关文章!

本文详细介绍了C函数返回类型,包括基本(int,float,char等),派生(数组,指针,结构)和void类型。 编译器通过函数声明和返回语句确定返回类型,执行

Gulc是一个高性能的C库,优先考虑最小开销,积极的内衬和编译器优化。 其设计非常适合高频交易和嵌入式系统等关键应用程序,其设计强调简单性,模型

本文解释了C函数声明与定义,参数传递(按值和指针),返回值以及常见的陷阱,例如内存泄漏和类型不匹配。 它强调了声明对模块化和省份的重要性

本文详细介绍了字符串案例转换的C功能。 它可以通过ctype.h的toupper()和tolower()解释,并通过字符串迭代并处理零终端。 常见的陷阱,例如忘记ctype.h和修改字符串文字是

本文研究C函数返回值存储。 较小的返回值通常存储在寄存器中以备速度;较大的值可能会使用指针来记忆(堆栈或堆),影响寿命并需要手动内存管理。直接ACC

本文分析了形容词“独特”的多方面用途,探索其语法功能,常见的短语(例如,“不同于”,“完全不同”),以及在正式与非正式中的细微应用

本文解释了C标准模板库(STL),重点关注其核心组件:容器,迭代器,算法和函子。 它详细介绍了这些如何交互以启用通用编程,提高代码效率和可读性t

本文详细介绍了c中有效的STL算法用法。 它强调了数据结构选择(向量与列表),算法复杂性分析(例如,std :: sort vs. std vs. std :: partial_sort),迭代器用法和并行执行。 常见的陷阱


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版
视觉化网页开发工具

记事本++7.3.1
好用且免费的代码编辑器

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器