Ardalis.Specific は、主に Entity Framework Core 用に設計された、データベースのクエリの仕様パターンを有効にする強力なライブラリですが、ここでは、Ardalis.Specific を拡張して使用できるようにする方法を示します。 NHibernate も ORM として機能します。
このブログ投稿は、Ardalis.仕様についてある程度の経験があり、NHibernate を使用するプロジェクトでそれを使用したいと考えていることを前提としています。 Ardalis.仕様にまだ慣れていない場合は、ドキュメントにアクセスして詳細を確認してください。
まず、Hibernate にはクエリを実行するための 3 つの異なる組み込み方法があります
- クエリへの Linq (IQueryable を使用)
- 基準 API
- クエリオーバー
3 つの方法すべてを処理できるように Ardalis.Spec を拡張する方法を説明しますが、Linq to Query は Entity Framework Core と同様に IQueryable でも動作するため、最初にそのオプションを説明します。
クエリへのリンク
結合関係の作成に関しては、Entity Framework Core と NHIbernate の間には若干の違いがあります。 Entity Framework Core には、IQueryable の拡張メソッドである Include と thenInclude があります (これらは、Ardalis.仕様で使用されるメソッド名でもあります)。
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>
次に、FetchEvaluator (および他のエバリュエーター) を使用するように ISpecificEvaluator を構成する必要があります。次のように、コンストラクターで構成されたエバリュエーターを使用して、実装 ISpecifyEvaluator を追加します。 WhereEvaluator、OrderEvaluator、および PaginationEvaluator はすべて Ardalis.仕様に含まれており、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>
これで、次のような LinqToQuerySpecEvaluator への参照をリポジトリに作成できます。
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>
それだけです。通常 Ardalis.仕様:
を使用するのと同じように、仕様で Linq to Query を使用できるようになりました。
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 API と Query Over には SQL を生成するための独自の実装があり、IQueryable を使用しないため、IEvaluator インターフェイスと互換性がありません。私の解決策は、この場合、これらのメソッドに IEvaluator インターフェイスを使用することを避け、仕様パターンの利点に焦点を当てることです。でも、ミックスもできるようになりたいです
私のソリューションでは、Linq to Query、Criteria、および Query Over を使用しています (これらの実装の 1 つだけが必要な場合は、最適なニーズに合わせて選択できます)。
これを行うには、仕様または仕様を継承する 4 つの新しいクラスを追加します
注: これらのクラスを定義するアセンブリには、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() メソッドは、クエリを 1 行に単純化する拡張メソッドです。
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 への参照が必要です。これは NHibernate
にあります。
public class TrackByNameCriteria : CriteriaSpecification<track> { public TrackByNameCriteria(string trackName) { this.UseCriteria(criteria => criteria.Add(Restrictions.Eq(nameof(Track.Name), trackName))); } } </track>
仕様に対するクエリの例
注: これらのクラスを定義するアセンブリには、QueryOver のアクションを定義するため、NHibernate への参照が必要です。これは NHibernate
にあります。
public class TrackByNameQueryOver : QueryOverSpecification<track> { public TrackByNameQueryOver(string trackName) { this.UseQueryOver(queryOver => queryOver.Where(x => x.Name == trackName)); } } </track>
NHibernate 用に Ardalis.仕様を拡張することで、Linq to Query、Criteria API、Query Over をすべて単一のリポジトリ パターン内で使用できるようになります。このアプローチは、NHibernate ユーザーに適応性の高い強力なソリューションを提供します
以上がLinq、Criteria API、Query Over を使用した NHibernate の Ardalis.仕様の拡張の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

この記事では、c関数のリターンタイプ、基本(int、float、charなど)、派生(配列、ポインター、構造体)、およびvoid型を含む詳細を示します。 コンパイラは、関数宣言とreturnステートメントを介して返品タイプを決定し、強制します

GULCは、最小限のオーバーヘッド、積極的なインライン、およびコンパイラの最適化を優先する高性能Cライブラリです。 高周波取引や組み込みシステムなどのパフォーマンスクリティカルなアプリケーションに最適な設計では、シンプルさ、モジュールが強調されています

この記事では、文字列ケース変換のC関数について詳しく説明しています。 ctype.hのtoupper()とtolower()を使用し、文字列を介して繰り返し、ヌルターミネーターを処理することを説明しています。 ctype.hを忘れたり、文字列リテラルを変更するなどの一般的な落とし穴は

この記事では、C関数宣言と定義、引数の合格(価値とポインターによる)、返品値、およびメモリリークやタイプの不一致などの一般的な落とし穴について説明します。 モジュール性とProviの宣言の重要性を強調しています

この記事では、C関数の戻り値ストレージを調べます。 通常、リターン値は通常、速度のためにレジスタに保存されます。値が大きいと、ポインターをメモリ(スタックまたはヒープ)に使用し、寿命に影響を与え、手動のメモリ管理が必要になります。直接acc

この記事では、形容詞の「個別」の多面的な使用法を分析し、その文法機能、一般的なフレーズ(例:「はっきりと異なる」とは異なる」、およびフォーマルと非公式の微妙なアプリケーションを調査します。

この記事では、cの効率的なSTLアルゴリズムの使用について詳しく説明しています。 データ構造の選択(ベクトル対リスト)、アルゴリズムの複雑さ分析(STD :: STD :: STD :: PARTIAL_SORTなど)、イテレーターの使用、および並列実行を強調しています。 のような一般的な落とし穴

この記事では、C標準テンプレートライブラリ(STL)について説明し、そのコアコンポーネント(コンテナ、イテレーター、アルゴリズム、およびファンクター)に焦点を当てています。 これらが一般的なプログラミングを有効にし、コード効率を向上させ、読みやすさを改善する方法を詳述しています。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

Dreamweaver Mac版
ビジュアル Web 開発ツール

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。
