Using C# dynamic type to build a datalayer

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM) – Big Mike

I have always been fascinated by the dynamic keyword that was introduced in C# 4.0, but never got around to looking deeper into it…until today.

I decided to build a mock orm-ish datalayer by using the various features that came with the dynamic type.

Querying

All that the class above does is new up the dynamic database and cast it to the dynamic type.

My true database class inherits from System.Dynamic.DynamicObject, which enables me to specify the dynamic behavior at run time. For example, I’ve overriden the TryGetMember method, so that any attempt to access a property will create a query builder whose name would be that of the property the user tried to call.

Below’s the query builder itself. Overriding the TryInvokemember enables me to capture methods calls on my dynamic object. Based on the name of the method, I decide what type of query to build.

Reading the data

In order to read back the data, I rely on the System.Data.DataTable. Notice that I do not actually make any attempt anywhere in my code to fetch the data from database. That part can be easily achieved using the SqlDataAdapter (or the OracleDataAdapter for Oracle’s ODP.NET), which allows you to retrieve data in the form of a DataTable.

How to use it

Lets assume we have a “Persons” table that maps to the class defined below. Say I wanted to build a query to get me all of the persons in the database based on their name. Assuming we run this query with a DbDataAdapter and populate the DataTable, here’s the code that would create my Person object.

This, of course, is just some sample code. You would preferably encapsulate the read better. For more samples, please take a look that Tests on the GitHub repository.

Advertisements

Using C# dynamic type to build a datalayer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s