検索
ホームページバックエンド開発C++Linq、Criteria API、Query Over を使用した NHibernate の Ardalis.仕様の拡張

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

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 サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
CおよびXML:プロジェクトにデータを統合しますCおよびXML:プロジェクトにデータを統合しますMay 10, 2025 am 12:18 AM

CプロジェクトにXMLを統合することは、次の手順を通じて達成できます。1)PUGIXMLまたはTinyXMLライブラリを使用してXMLファイルを解析および生成すること、2)解析のためのDOMまたはSAXメソッドを選択、3)ネストされたノードとマルチレベルのプロパティを処理する、4)デバッグ技術と最高の慣行を使用してパフォーマンスを最適化します。

CでXMLを使用する:ライブラリとツールのガイドCでXMLを使用する:ライブラリとツールのガイドMay 09, 2025 am 12:16 AM

XMLは、特に構成ファイル、データストレージ、ネットワーク通信でデータを構成するための便利な方法を提供するため、Cで使用されます。 1)tinyxml、pugixml、rapidxmlなどの適切なライブラリを選択し、プロジェクトのニーズに従って決定します。 2)XML解析と生成の2つの方法を理解する:DOMは頻繁にアクセスと変更に適しており、SAXは大規模なファイルまたはストリーミングデータに適しています。 3)パフォーマンスを最適化する場合、TinyXMLは小さなファイルに適しています。PugixMLはメモリと速度でうまく機能し、RapidXMLは大きなファイルの処理に優れています。

C#およびC:さまざまなパラダイムの探索C#およびC:さまざまなパラダイムの探索May 08, 2025 am 12:06 AM

C#とCの主な違いは、メモリ管理、多型の実装、パフォーマンスの最適化です。 1)C#はゴミコレクターを使用してメモリを自動的に管理し、Cは手動で管理する必要があります。 2)C#は、インターフェイスと仮想方法を介して多型を実現し、Cは仮想関数と純粋な仮想関数を使用します。 3)C#のパフォーマンスの最適化は、構造と並列プログラミングに依存しますが、Cはインライン関数とマルチスレッドを通じて実装されます。

C XML解析:テクニックとベストプラクティスC XML解析:テクニックとベストプラクティスMay 07, 2025 am 12:06 AM

DOMおよびSAXメソッドを使用して、CのXMLデータを解析できます。1)DOMのXMLをメモリに解析することは、小さなファイルに適していますが、多くのメモリを占有する可能性があります。 2)サックス解析はイベント駆動型であり、大きなファイルに適していますが、ランダムにアクセスすることはできません。適切な方法を選択してコードを最適化すると、効率が向上する可能性があります。

特定のドメインのc:その拠点の調査特定のドメインのc:その拠点の調査May 06, 2025 am 12:08 AM

Cは、高性能と柔軟性のため、ゲーム開発、組み込みシステム、金融取引、科学的コンピューティングの分野で広く使用されています。 1)ゲーム開発では、Cは効率的なグラフィックレンダリングとリアルタイムコンピューティングに使用されます。 2)組み込みシステムでは、Cのメモリ管理とハードウェア制御機能が最初の選択肢になります。 3)金融取引の分野では、Cの高性能はリアルタイムコンピューティングのニーズを満たしています。 4)科学的コンピューティングでは、Cの効率的なアルゴリズムの実装とデータ処理機能が完全に反映されています。

神話を暴く:Cは本当に死んだ言語ですか?神話を暴く:Cは本当に死んだ言語ですか?May 05, 2025 am 12:11 AM

Cは死んでいませんが、多くの重要な領域で栄えています。1)ゲーム開発、2)システムプログラミング、3)高性能コンピューティング、4)ブラウザとネットワークアプリケーション、Cは依然として主流の選択であり、その強力な活力とアプリケーションのシナリオを示しています。

C#対C:プログラミング言語の比較分析C#対C:プログラミング言語の比較分析May 04, 2025 am 12:03 AM

C#とCの主な違いは、構文、メモリ管理、パフォーマンスです。1)C#構文は最新であり、LambdaとLinqをサポートし、CはC機能を保持し、テンプレートをサポートします。 2)C#はメモリを自動的に管理し、Cは手動で管理する必要があります。 3)CパフォーマンスはC#よりも優れていますが、C#パフォーマンスも最適化されています。

Cを使用したXMLアプリケーションの構築:実用的な例Cを使用したXMLアプリケーションの構築:実用的な例May 03, 2025 am 12:16 AM

tinyxml、pugixml、またはlibxml2ライブラリを使用して、CでXMLデータを処理できます。1)XMLファイルを解析する:DOMまたはSAXメソッドを使用し、DOMは小さなファイルに適しており、SAXは大きなファイルに適しています。 2)XMLファイルを生成:データ構造をXML形式に変換し、ファイルに書き込みます。これらの手順を通じて、XMLデータを効果的に管理および操作できます。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

SecLists

SecLists

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

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター