The following document is targeting developers who wish to implement a custom query translator for a DBMS that is not yet supported.

 

Step 1 – Subclass the DbExpressionTranslator class.

The DbExpressionTranslator class is an abstract class that the new query translator must inherit from.

This class takes care of visiting each node in the expression tree and the the concrete query translator is responsible for returning the required syntax for each expression type.

For instance, the SqlQueryTranslator class translates a DbColumnExpression into SQL using the following code.

  1. protected override DbExpression VisitColumnExpression(DbColumnExpression columnExpression)
  2. {
  3.     var sqlFragment = QuoteIdentifier(columnExpression.ColumnName);
  4.     return ExpressionFactory.Sql(sqlFragment);
  5. }

 

It might be a good idea to copy the code that is present in the SqlQueryTranslator or the MySqlQueryTransator and use this as a starting point for the new query translator.

Even though some expressions are translated in the same across translators, it is recommended that you don’t inherit from another concrete translator.

 

Step 2 – Subclass the DbExpressionSyntaxTests  class

Every translator needs a lot of tests to verify that it produces the correct syntax according to the target SQL dialect.

The good news is that all the tests are already written and you just need to provide the correct syntax for each expression type.

For instance, the SqlExpressionSyntaxTests class overrides the ColumnExpressionSyntax method to provide a valid column syntax for Sql Server.

  1. public override string ColumnExpressionSyntax
  2. {
  3.     get { return "[SomeColumn]"; }
  4. }

 

Once all the tests have passed, the query translator is pretty much finished.

 

Step 3 – Register the new query translator

There are two methods to register the new translator

Using configuration

We can add a new provider using this configuration (App/Web.config)

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3.   <configSections>
  4.     <section name="dbExpressions" type ="DbExpressions.Configuration.DbExpressionSettings, DbExpressions"/>
  5.   </configSections>
  6.   <dbExpressions>
  7.     <queryTranslators>
  8.       <queryTranslator providerName="InvariantProviderName", type ="TranslatorTypeName, TranslatorAssembly"></queryTranslator>
  9.     </queryTranslators>
  10.   </dbExpressions>
  11. </configuration>

 

Using code

We can also register the new translator using the static DbQueryTranslatorFactory class.

  1. DbQueryTranslatorFactory.RegisterQueryTranslator("System.Data.SqlClient",typeof(SqlQueryTranslator));

Last edited Jan 24, 2011 at 8:38 PM by seesharper, version 1

Comments

No comments yet.