QueryExpressionBuilder

Library for building Predicate Expression from query models
git clone git://185.198.27.126/QueryExpressionBuilder.git
Log | Files | Refs | README

commit c7692bb523fad5cdfc35c972d415d240d941266d
parent 27586ec9fc92f058715c392254a100c1d5f2dc02
Author: novickii.sergei.nure@gmail.com <novickii.sergei.nure@gmail.com>
Date:   Mon, 29 Apr 2024 17:04:15 +0300

New attributes: Contains and Equals

Diffstat:
A.nuspec | 15+++++++++++++++
MQueryExpressionBuilder.sln | 2+-
MQueryExpressionBuilder/Attributes.cs | 32++++++++++++++++++++++++++++++--
MQueryExpressionBuilder/ExpressionBuilder.cs | 29+++++++++++++++++++++++++++--
MREADME.md | 4++++
5 files changed, 77 insertions(+), 5 deletions(-)

diff --git a/.nuspec b/.nuspec @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="utf-8"?> +<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> + <metadata> + <!-- Required elements--> + <id>QueryExpressionBuilder</id> + <version>1.0.0.0</version> + <description>This library helps create a predicate function for filtering database queries based on a model.</description> + <authors>Created by Taogar. </authors> + <licenseUrl>This project is distributed under the [MIT](https://opensource.org/licenses/MIT) license, which allows free use, modification, and distribution of the code in accordance with the terms of the MIT license.</licenseUrl> + <!-- Optional elements --> + <!-- ... --> + </metadata> + <!-- Optional 'files' node --> +</package> +\ No newline at end of file diff --git a/QueryExpressionBuilder.sln b/QueryExpressionBuilder.sln @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.9.34511.98 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QueryExpressionBuilder", "QueryExpressionBuilder\QueryExpressionBuilder.csproj", "{C6B925B3-E450-4830-9B40-305102A14309}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QueryExpressionBuilder", "QueryExpressionBuilder\QueryExpressionBuilder.csproj", "{C6B925B3-E450-4830-9B40-305102A14309}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/QueryExpressionBuilder/Attributes.cs b/QueryExpressionBuilder/Attributes.cs @@ -20,6 +20,16 @@ { } } + + /// <summary> + /// Filtration by contains function + /// </summary> + public class ContainsAttribute : BasePredicateAttribute + { + public ContainsAttribute(string propertyName) : base (propertyName) + { + } + } } /// <summary> @@ -28,7 +38,7 @@ public class Numbers { /// <summary> - /// Filtration func >= + /// Filtration func GreaterOrEqual /// </summary> [AttributeUsage(AttributeTargets.Property)] public class GreaterOrEqualAttribute : BasePredicateAttribute @@ -42,7 +52,7 @@ } /// <summary> - /// Filtration func <= + /// Filtration func LessOrEqual /// </summary> [AttributeUsage(AttributeTargets.Property)] public class LessOrEqualAttribute : BasePredicateAttribute @@ -54,6 +64,17 @@ { } } + + /// <summary> + /// Filtration by equals function + /// </summary> + public class EqualsAttribute : BasePredicateAttribute + { + public EqualsAttribute(string propertyName) : base(propertyName) + { + + } + } } /// <summary> @@ -62,8 +83,15 @@ [AttributeUsage(AttributeTargets.Property)] public class BasePredicateAttribute : Attribute { + /// <summary> + /// Name of property in DB + /// </summary> public string PropertyName { get; set; } + /// <summary> + /// Constructor with name of property in DB + /// </summary> + /// <param name="propertyName"></param> public BasePredicateAttribute(string propertyName) { PropertyName = propertyName; diff --git a/QueryExpressionBuilder/ExpressionBuilder.cs b/QueryExpressionBuilder/ExpressionBuilder.cs @@ -87,7 +87,8 @@ namespace QueryExpressionBuilder //Только те свойства которые помечены атрибутами var T_pr_props = typeof(TQE).GetProperties().Where(prop => prop.GetCustomAttribute<LessOrEqualAttribute>() != null || - prop.GetCustomAttribute<GreaterOrEqualAttribute>() != null || prop.GetCustomAttribute<StartWithAttribute>() != null).ToArray(); + prop.GetCustomAttribute<GreaterOrEqualAttribute>() != null || prop.GetCustomAttribute<StartWithAttribute>() != null || + prop.GetCustomAttribute<ContainsAttribute>() != null || prop.GetCustomAttribute<EqualsAttribute>() != null).ToArray(); //Проходимся по всем параметрам класса БД foreach (var p in typeof(TDB).GetProperties()) @@ -97,7 +98,18 @@ namespace QueryExpressionBuilder { if (y.GetCustomAttribute<StartWithAttribute>() != null) { - var propertyY = Expression.Property(userParameter, y.Name); + var propertyY = Expression.Property(userParameter, p.Name); + var propertyP = Expression.Property(userParameter, p.Name); + var containsCall = Expression.Call(propertyP, "StartsWith", null, Expression.Constant(y.GetValue(query), typeof(string))); + var obj = y.GetValue(query); + if (obj != null) + { + conditions.Add(containsCall); + } + } + else if(y.GetCustomAttribute<ContainsAttribute>() != null) + { + var propertyY = Expression.Property(userParameter, p.Name); var propertyP = Expression.Property(userParameter, p.Name); var containsCall = Expression.Call(propertyP, "Contains", null, Expression.Constant(y.GetValue(query), typeof(string))); var obj = y.GetValue(query); @@ -132,6 +144,19 @@ namespace QueryExpressionBuilder conditions.Add(condition); } } + else if(y.GetCustomAttribute<EqualsAttribute>() != null) + { + var propertyName = y.GetCustomAttribute<EqualsAttribute>().PropertyName; + var propertyY = Expression.Property(userParameter, propertyName); + var obj = y.GetValue(query); + if (obj != null) + { + var value = Convert.ChangeType(obj, p.PropertyType); + var constantValue = Expression.Constant(value, p.PropertyType); + var condition = Expression.Equal(propertyY, constantValue); + conditions.Add(condition); + } + } } } diff --git a/README.md b/README.md @@ -11,10 +11,12 @@ Currently, there are 3 attributes:<br> Namespace QueryExpressionBuilder.Attributes.String - attributes for properties of type String<br> StartWithAttribute - Indicates that a filter equivalent to the System.String.StartWith() function will be used for the property.<br> +ContainsAttribute - Indicates that a filter equivalent to the System.String.Contains() function will be used for the property.<br> Namespace QueryExpressionBuilder.Attributes.Numbers - attribute for all properties that are numeric, including DateTime<br> GreaterOrEqualAttribute - Indicates that a filter equivalent to the >= conditional expression will be used for the property.<br> LessOrEqualAttribute - Indicates that a filter equivalent to the <= conditional expression will be used for the property.<br> +EqualsAttribute - Just compares values like in a function Equals.<br> You need to pass the property name from the class representing the entity in the database to the attribute constructor. @@ -122,10 +124,12 @@ This project is distributed under the [MIT](https://opensource.org/licenses/MIT) Пространство имен QueryExpressionBuilder.Attributes.String - атрибуты для свойств типа String<br> StartWithAttribute - Означает, что дял свойства будет использоватся фильтр с аналогом функции System.String.StartWith()<br> +ContainsAttribute - Означает, что дял свойства будет использоватся фильтр с аналогом функции System.String.Contains()<br> Пространство имен QueryExpressionBuilder.Attributes.Numbers - атрибут для всех свойств которые ввляются числовыми, в том числе DateTime<br> GreaterOrEqualAttribute - Означает, что для свойства будет использоваться фильтр с аналогом условного выражения >=<br> LessOrEqualAttribute - Означает, что для свойства будет использоваться фильтр с аналогом условного выражения <=<br> +EqualsAttribute - Просто то же самое, что и Equals.<br> В конструктор атрибута необходимо передать название свойства из класса представляющий сущьность в БД.<br>