How to work with objects of unknown type returned from DataContext.ExecuteQuery

So, with the advent of the dynamic keyword in C # 4.0, I hope that I can find a better solution to the problem of handling the types returned by DataContext.ExecuteQuery when arbitrary columns are selected.

In the past, I either created a new type to store the result of such a query, or used the method described in this SO post . So, now that I can work on a new project under .NET 4.0, I was learning to use a dynamic type to do the same in a less painful way.

So, I did this:

 var result = _db.ExecuteQuery<dynamic>( "SELECT CustomerID,City FROM Customers", new object[0] ); foreach( var d in result ) { MessageBox.Show( String.Format( "{0}, {1}", d.CustomerID, d.City ) ); } 

An exception occurs at run time because the CustomerID property does not exist for the dynamic object. So, since my experience with the dynamic keyword at the moment is nil (article or blog post or two, no real experience), I was hoping that someone here could tell me if what I am trying to do here is possible . I probably overestimate the amount of β€œmagic” behind ExecuteQuery, but I thought this might work due to matching properties behind the scenes. Any help is greatly appreciated.

+4
source share
2 answers

More recently, we wrote a dapper that perfectly matches the original question:

 var result = connection.Query( "SELECT CustomerID,City FROM Customers"); foreach( var d in result ) { MessageBox.Show( String.Format( "{0}, {1}", d.CustomerID, d.City ) ); } 

It allows parameters, etc., and there is a (preferred) typed API via Query<T> , but the dynamic API also works fine.

+5
source

The mapping is done by checking T and using reflection - and dynamic - really just a fancy word for object in this context. For now, you might just need to create a type that matches the expected location.

You can try switching to Tuple<int,string> , but I have not tried this, and I'm not sure what it will understand to map ctor arg 0 to col 0, etc.

I use the code as in the question quite a bit, and creating a meaningful stub class is usually not a problem, especially with automatically implemented properties.

+1
source

Source: https://habr.com/ru/post/1340127/


All Articles