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 項目中集成XML可以通過以下步驟實現:1)使用pugixml或TinyXML庫解析和生成XML文件,2)選擇DOM或SAX方法進行解析,3)處理嵌套節點和多級屬性,4)使用調試技巧和最佳實踐優化性能。

在C 中使用XML是因為它提供了結構化數據的便捷方式,尤其在配置文件、數據存儲和網絡通信中不可或缺。 1)選擇合適的庫,如TinyXML、pugixml、RapidXML,根據項目需求決定。 2)了解XML解析和生成的兩種方式:DOM適合頻繁訪問和修改,SAX適用於大文件或流數據。 3)優化性能時,TinyXML適合小文件,pugixml在內存和速度上表現好,RapidXML處理大文件優異。

C#和C 的主要區別在於內存管理、多態性實現和性能優化。 1)C#使用垃圾回收器自動管理內存,C 則需要手動管理。 2)C#通過接口和虛方法實現多態性,C 使用虛函數和純虛函數。 3)C#的性能優化依賴於結構體和並行編程,C 則通過內聯函數和多線程實現。

C 中解析XML數據可以使用DOM和SAX方法。 1)DOM解析將XML加載到內存,適合小文件,但可能佔用大量內存。 2)SAX解析基於事件驅動,適用於大文件,但無法隨機訪問。選擇合適的方法並優化代碼可提高效率。

C 在遊戲開發、嵌入式系統、金融交易和科學計算等領域中的應用廣泛,原因在於其高性能和靈活性。 1)在遊戲開發中,C 用於高效圖形渲染和實時計算。 2)嵌入式系統中,C 的內存管理和硬件控制能力使其成為首選。 3)金融交易領域,C 的高性能滿足實時計算需求。 4)科學計算中,C 的高效算法實現和數據處理能力得到充分體現。

C 沒有死,反而在許多關鍵領域蓬勃發展:1)遊戲開發,2)系統編程,3)高性能計算,4)瀏覽器和網絡應用,C 依然是主流選擇,展現了其強大的生命力和應用場景。

C#和C 的主要區別在於語法、內存管理和性能:1)C#語法現代,支持lambda和LINQ,C 保留C特性並支持模板。 2)C#自動內存管理,C 需要手動管理。 3)C 性能優於C#,但C#性能也在優化中。

在C 中處理XML數據可以使用TinyXML、Pugixml或libxml2庫。 1)解析XML文件:使用DOM或SAX方法,DOM適合小文件,SAX適合大文件。 2)生成XML文件:將數據結構轉換為XML格式並寫入文件。通過這些步驟,可以有效地管理和操作XML數據。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能