| 
 | 1 | +---  | 
 | 2 | +title: Converting Filter and Sort Descriptors to SQL Queries in Blazor Grid  | 
 | 3 | +description: Learn how to parse filter and sort descriptors from the Blazor Grid into SQL query statements for manual SQL queries execution using the OnRead event.  | 
 | 4 | +type: how-to  | 
 | 5 | +page_title: How to Parse Blazor Grid Descriptors into SQL Query Statements  | 
 | 6 | +slug: grid-convert-descriptors-to-sql  | 
 | 7 | +tags: grid, blazor, filter descriptors , sort descriptors, SQL query  | 
 | 8 | +res_type: kb  | 
 | 9 | +ticketid: 1666625, 1653361  | 
 | 10 | +---  | 
 | 11 | + | 
 | 12 | +## Environment  | 
 | 13 | + | 
 | 14 | +<table>  | 
 | 15 | +    <tbody>  | 
 | 16 | +        <tr>  | 
 | 17 | +            <td>Product</td>  | 
 | 18 | +            <td>Grid for Blazor</td>  | 
 | 19 | +        </tr>  | 
 | 20 | +    </tbody>  | 
 | 21 | +</table>  | 
 | 22 | + | 
 | 23 | +## Description  | 
 | 24 | + | 
 | 25 | +When using the Grid [`OnRead` event]({%slug grid-events%}#read-event) to execute SQL queries, I need to convert the Grid's filter and sort descriptors into SQL query statements. This way I can create SQL clauses for filtering and ordering items directly through SQL.  | 
 | 26 | + | 
 | 27 | +This KB article also answers the following questions:  | 
 | 28 | +- How can I convert Grid filters and sorters to SQL `WHERE` and `ORDER BY` clauses?  | 
 | 29 | +- Is there a way to parse Grid filter and sort descriptors into SQL queries?  | 
 | 30 | +- Can I use [`DataSourceRequest`]({%slug common-features-data-binding-onread%}#event-argument) to generate SQL query statements for filtering and sorting?  | 
 | 31 | + | 
 | 32 | +## Solution  | 
 | 33 | + | 
 | 34 | +To convert the Grid's filter and sort descriptors into SQL query statements, you need to manually construct the SQL query within the `OnRead` event handler by utilizing the `args.Request.Filters` and `args.Request.Sorts` objects. Although Telerik UI for Blazor does not provide a direct method to extract the SQL query from the `DataSourceRequest`, you can achieve this manually.  | 
 | 35 | + | 
 | 36 | +The following steps outline how to achieve this:  | 
 | 37 | + | 
 | 38 | +1. Add an `OnRead` event to your Grid and in the event handler, access the `args.Request.Filters` and `args.Request.Sorts` to construct your SQL query.  | 
 | 39 | +1. Iterate through `args.Request.Filters` to construct the `WHERE` clause of your SQL query. Each filter in this collection will correspond to a column filter in the Grid.  | 
 | 40 | +1. Iterate through `args.Request.Sorts` to build the `ORDER BY` clause of your SQL query. Each sort descriptor corresponds to a column sorting in the Grid.  | 
 | 41 | +1. Form your complete SQL query and execute it against your database with the constructed `WHERE` and `ORDER BY` clauses.  | 
 | 42 | +1. Assign the result of your SQL query to the Grid by setting `args.Data`.  | 
 | 43 | + | 
 | 44 | +## Example  | 
 | 45 | + | 
 | 46 | +Below is a simplified example demonstrating how to parse filter and sort descriptors. This example does not directly execute a SQL query but outlines how to construct the `WHERE` and `ORDER BY` clauses.  | 
 | 47 | + | 
 | 48 | +```csharp  | 
 | 49 | +@using System.Text  | 
 | 50 | +@using Telerik.DataSource  | 
 | 51 | +@using Telerik.DataSource.Extensions  | 
 | 52 | + | 
 | 53 | +<TelerikGrid TItem="@MyItem"  | 
 | 54 | +             OnRead="@ReadItems"  | 
 | 55 | +             FilterMode="@GridFilterMode.FilterRow"  | 
 | 56 | +             Sortable="true"  | 
 | 57 | +             Pageable="true">  | 
 | 58 | +    <GridColumns>  | 
 | 59 | +        <GridColumn Field=@nameof(MyItem.ID) />  | 
 | 60 | +        <GridColumn Field=@nameof(MyItem.Name) />  | 
 | 61 | +        <GridColumn Field=@nameof(MyItem.Age) />  | 
 | 62 | +    </GridColumns>  | 
 | 63 | +</TelerikGrid>  | 
 | 64 | + | 
 | 65 | +@code {  | 
 | 66 | +    private List<MyItem> GridData { get; set; } = new();  | 
 | 67 | + | 
 | 68 | +    private async Task ReadItems(GridReadEventArgs args)  | 
 | 69 | +    {  | 
 | 70 | +        string sqlQuery = string.Empty;  | 
 | 71 | +        string filterQuery = BuildFilterQuery(args.Request.Filters);  | 
 | 72 | +        string sortQuery = BuildSortQuery(args.Request.Sorts);  | 
 | 73 | + | 
 | 74 | +        if (filterQuery != string.Empty)  | 
 | 75 | +        {  | 
 | 76 | +            sqlQuery = $"SELECT * FROM MyTable WHERE {filterQuery}";  | 
 | 77 | + | 
 | 78 | +            GridData = await ExecuteSqlQuery(sqlQuery);  | 
 | 79 | +        }  | 
 | 80 | +        else if (sortQuery != string.Empty)  | 
 | 81 | +        {  | 
 | 82 | +            sqlQuery = $"SELECT * FROM MyTable ORDER BY {sortQuery}";  | 
 | 83 | + | 
 | 84 | +            GridData = await ExecuteSqlQuery(sqlQuery);  | 
 | 85 | +        }  | 
 | 86 | +        else  | 
 | 87 | +        {  | 
 | 88 | +            GridData = GenerateData();  | 
 | 89 | +        }  | 
 | 90 | + | 
 | 91 | +        var datasourceResult = GridData.ToDataSourceResult(args.Request);  | 
 | 92 | + | 
 | 93 | +        args.Data = datasourceResult.Data;  | 
 | 94 | +        args.Total = datasourceResult.Total;  | 
 | 95 | +    }  | 
 | 96 | + | 
 | 97 | +    private string BuildFilterQuery(IEnumerable<IFilterDescriptor> filters)  | 
 | 98 | +    {  | 
 | 99 | +        // Implement logic to parse filters into SQL WHERE clause  | 
 | 100 | +        // Example: "Name = 'John' AND Age > 30"  | 
 | 101 | +        // You may need to adjust the SQL query depending if there are  | 
 | 102 | +        // more FilterDescriptors (when using FilterMenu filter mode)  | 
 | 103 | +        var filterQuery = new StringBuilder();  | 
 | 104 | +        foreach (var filter in filters)  | 
 | 105 | +        {  | 
 | 106 | +            if (filter is CompositeFilterDescriptor compositeFilter)  | 
 | 107 | +            {  | 
 | 108 | +                foreach (var childFilter in compositeFilter.FilterDescriptors)  | 
 | 109 | +                {  | 
 | 110 | +                    filterQuery.Append(ParseFilterDescriptor(childFilter));  | 
 | 111 | +                }  | 
 | 112 | +            }  | 
 | 113 | +        }  | 
 | 114 | +        return filterQuery.ToString();  | 
 | 115 | +    }  | 
 | 116 | + | 
 | 117 | +    private string ParseFilterDescriptor(IFilterDescriptor filter)  | 
 | 118 | +    {  | 
 | 119 | +        if (filter is FilterDescriptor descriptor)  | 
 | 120 | +        {  | 
 | 121 | +            return $"{descriptor.Member} {GetSqlOperator(descriptor.Operator)} '{descriptor.Value}'";  | 
 | 122 | +        }  | 
 | 123 | +        return string.Empty;  | 
 | 124 | +    }  | 
 | 125 | + | 
 | 126 | +    private string GetSqlOperator(FilterOperator filterOperator)  | 
 | 127 | +    {  | 
 | 128 | +        return filterOperator switch  | 
 | 129 | +        {  | 
 | 130 | +            FilterOperator.IsEqualTo => "=",  | 
 | 131 | +            FilterOperator.IsNotEqualTo => "<>",  | 
 | 132 | +            FilterOperator.IsGreaterThan => ">",  | 
 | 133 | +            FilterOperator.IsGreaterThanOrEqualTo => ">=",  | 
 | 134 | +            FilterOperator.IsLessThan => "<",  | 
 | 135 | +            FilterOperator.IsLessThanOrEqualTo => "<=",  | 
 | 136 | +            FilterOperator.Contains => "LIKE",  | 
 | 137 | +            _ => throw new NotSupportedException($"Operator {filterOperator} is not supported")  | 
 | 138 | +        };  | 
 | 139 | +    }  | 
 | 140 | + | 
 | 141 | +    private string BuildSortQuery(IEnumerable<SortDescriptor> sorts)  | 
 | 142 | +    {  | 
 | 143 | +        // Implement logic to parse sorters into SQL ORDER BY clause  | 
 | 144 | +        // Example: "Name ASC"  | 
 | 145 | +        return string.Join(", ", sorts.Select(s => $"{s.Member} {(s.SortDirection == ListSortDirection.Ascending ? "ASC" : "DESC")}"));  | 
 | 146 | +    }  | 
 | 147 | + | 
 | 148 | +    private async Task<List<MyItem>> ExecuteSqlQuery(string sqlQuery)  | 
 | 149 | +    {  | 
 | 150 | +        // Implement logic to execute the SQL query and return the result  | 
 | 151 | +        // This is a placeholder for your actual data access code  | 
 | 152 | +
  | 
 | 153 | +        //Remove this line when you execute the SQL query  | 
 | 154 | +        //It is only for example purposes  | 
 | 155 | +        GridData = new List<MyItem>();  | 
 | 156 | +        return GridData;  | 
 | 157 | +    }  | 
 | 158 | + | 
 | 159 | +    protected override void OnInitialized()  | 
 | 160 | +    {  | 
 | 161 | +        GridData = GenerateData();  | 
 | 162 | +    }  | 
 | 163 | + | 
 | 164 | +    private List<MyItem> GenerateData()  | 
 | 165 | +    {  | 
 | 166 | +        var result = new List<MyItem>();  | 
 | 167 | +        var rand = new Random();  | 
 | 168 | +        for (int i = 0; i < 100; i++)  | 
 | 169 | +        {  | 
 | 170 | +            result.Add(new MyItem()  | 
 | 171 | +                {  | 
 | 172 | +                    ID = i,  | 
 | 173 | +                    Name = "Name " + i,  | 
 | 174 | +                    Age = rand.Next(10, 40)  | 
 | 175 | +                });  | 
 | 176 | +        }  | 
 | 177 | + | 
 | 178 | +        return result;  | 
 | 179 | +    }  | 
 | 180 | + | 
 | 181 | +    public class MyItem  | 
 | 182 | +    {  | 
 | 183 | +        public int ID { get; set; }  | 
 | 184 | +        public string Name { get; set; }  | 
 | 185 | +        public int Age { get; set; }  | 
 | 186 | +    }  | 
 | 187 | +}  | 
 | 188 | +```  | 
 | 189 | + | 
 | 190 | +## See Also  | 
 | 191 | + | 
 | 192 | +- [OnRead Event Documentation]({%slug grid-events%}#read-event)  | 
 | 193 | +- [Forum Post on Using DataSourceRequest in SQL Query](https://www.telerik.com/forums/can-datasourcerequest-be-used-in-sql-query-to-add-where-and-order-by-clauses)  | 
 | 194 | +- [Get Information From the DataSourceRequest]({%slug components/grid/manual-operations%}#get-information-from-the-datasourcerequest)  | 
0 commit comments