Important
This repository builds on the original NuGet package from >= .NET 10, updating the dependencies and adding support for OData 8 and $expand support. Please note that this version has been rewritten as a self-contained package and is not intended to be backwards compatible.
Dotnet NuGet package to convert OData query to SQL query when the data model is dynamic and hence entity framework or any other ORM with IQuerable support cannot be used. In a multi-tenant enterprise or Saas applications, the data model is usually not fixed (dynamic).
Let's consider you are building a Saas application for project and issue tracking, similar to Jira.
Development teams and organizations track issues differently, to personalize and measure their agile process.
Your Saas application provides this by allowing tenants to add properties(columns) to existing
object types(tables) or create completely new object types, it further allows querying new
object types and filtering using new properties through an OData service.
Contoso Inc, one of your tenant
- Adds a boolean property
InternaltoIssueobject. It is used to track internal vs customer reported issues. - Adds another object type called
Customerto track which customer reported the issue or was affected by it.Customerobject contains standard properties likeName,Emailetc.
It is not trivial to expose a multi-tenant OData service in such a scenario using Entity Framework since DB schema/EF's DBContext can be different for each tenant and can be modified on the fly.
GET https://api.trackerOne.com/contoso/odata/Issues?$filter=Internal eq true
GET https://api.trackerOne.com/contoso/odata/Customers?$filter=contains(Email,'outlook.com')
This project aims to solve this issue by providing a simple API to convert an OData query to an SQL query when the data model is dynamic.
- Install Nuget Package
Install-Package Melosso.DynamicODataToSQL
varconverter=newODataToSqlConverter(newEdmModelBuilder(),newSqlServerCompiler(){UseLegacyPagination=false});vartableName="Customers";varodataQueryParams=newDictionary<string,string>{{"select","Name, Email"},{"filter","contains(Email,'outlook.com')"},{"orderby","Name"},{"top","20"},{"skip","5"},};varresult=converter.ConvertToSQL(tableName,odataQueryParams,false);stringsql=result.Item1;// SELECT [Name], [Email] FROM [Customers] WHERE [Email] like @p0 ORDER BY [Name] ASC OFFSET @p1 ROWS FETCH NEXT @p2 ROWS ONLYIDictionary<string,object>sqlParams=result.Item2;// {"@p0", "%outlook.com%"},{"@p1", 5}, {"@p2", 20}See Unit tests for more examples
See DynamicODataSampleService for and example OData service.
Download AdventureWorks2019 Sample Database
Restore AdventureWorks2019 database.
Setup database user and permissions
CREATE LOGIN odata_service WITH PASSWORD ='Password123'; use AdventureWorks2019 CREATEUSERodata_service FOR LOGIN odata_service; GRANTSELECTON DATABASE::AdventureWorks2019 TO odata_service; GO
Run
dotnet run --project .\Samples\DynamicODataSampleService\DynamicODataSampleService.csprojUse Powershell to query the service, Top 10 Persons by ModifiedDate
Invoke-RestMethod'https://localhost:5001/tables/Person.Person?orderby=ModifiedDate desc&skip=0&top=10&select=FirstName,LastName,ModifiedDate'|ConvertTo-Json
Products with StockLevel less than 100
Invoke-RestMethod'https://localhost:5001/tables/Production.Product?filter=SafetyStockLevel lt 100'|ConvertTo-Json
- Supports basic OData syntax for
select,filter,skip,top,orderbyand nowapply - Currently does NOT support
expandandlambdaoperators. - You can now retrieve
SqlKata Queryinstead of SQL result. This is useful if you want to modify the query further using SqlKata. To do so simply useConvertToSQLKatamethod instead ofConvertToSQL.
All logical operators except
hasandinare supported.Grouping filters using
()is supported.String functions
startswith,endswithandcontainsare supported.DateTime functions
date,time,year,month,day,hourandminuteare supported.
Aggregations using Odata apply query option is supported. Spec: http://docs.oasis-open.org/odata/odata-data-aggregation-ext/v4.0/odata-data-aggregation-ext-v4.0.html
- Transformations:
filter,groupbyandaggregateare supported.expand,concat,search,top,bottomare NOT supported. sum,min,max,avg,countdistinctandcountare supported.
Example
\orders?$apply=groupby((Country),aggregate(Amount with sum as Total,Amount with average as AvgAmt))
is converted to
SELECT [Country], Sum(Amount) AS Total, Avg(Amount) AS AvgAmt FROM [Orders] GROUP BY [Country]For more advanced aggreagate scenarios supported, see unit tests.
By default filter values are checked if they can be converted to dates. Sometimes this is not expected. You can disable date parsing by setting up tryToParseDate to false on ConvertToSqlFromRawSql function.
Example
varconverter=newODataToSqlConverter(newEdmModelBuilder(),newSqlServerCompiler(){UseLegacyPagination=false});vartableName="Customers";converter.ConvertToSqlFromRawSql(customSqlQuery,oDataParams,false,false);varodataQueryParams=newDictionary<string,string>{{"select","Name, Type"},{"filter","Name eq '2022-11-30'"},};// Default conversion with Date Parsingvarresult=converter.ConvertToSQL(tableName,odataQueryParams,false);stringsql=result.Item1;// SELECT [Name], [Type] FROM [Products] WHERE [Name] = @p0IDictionary<string,object>sqlParams=resultWithoutParsedDates.Item2;// {"@p0", "11/30/2022 12:00:00 AM"}// Conversion without Date ParsingvarresultWithoutParsedDates=converter.ConvertToSQL(tableName,odataQueryParams,false,false);stringsql=resultWithoutParsedDates.Item1;// SELECT [Name], [Type] FROM [Products] WHERE [Name] = @p0IDictionary<string,object>sqlParams=resultWithoutParsedDates.Item2;// {"@p0", "2022-11-30"}You can now use custom query as source (instead of table) and be able to build query in response. WITH clause is used to wrap custom query.
Example
$apply=aggregate(TotalAmount with sum as TotalAmount, TotalAmount with average as AverageAmount,$count as OrderCount)varrawSql="SELECT * FROM [Orders]";converter.ConvertToSqlFromRawSql(customSqlQuery,oDataParams,count);is converted to
WITH [RawSql] AS (SELECT*FROM [Orders])
SELECTSum(TotalAmount) AS TotalAmount, AVG(TotalAmount) AS AverageAmount, COUNT(1) AS OrderCount FROM [RawSql] Check unit tests for more usage examples.
- Support for validating column names and column data types.
We are always looking for people to contribute! To find out how to help out, have a look at our Contributing Guide.
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
Copyright MIT © 2020 Vaibhav Goyal. See LICENSE for details.