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

In the past I have either created a new type to hold the result of such a query or used the method described in this SO post. So, now that I am able to work on a new project running under .NET 4.0, I looked into using a dynamic type to accomplish the same thing in a less painful manner.

So, I gave this a shot:

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 is thrown at runtime because the property CustomerID does not exist for the dynamic object. So, since my experience with the dynamic keyword to this point is nil (an article/blog post or two, no real experience) I was hoping someone here could let me know if what I am trying to do here is even possible. I am probably overestimating the amount of 'magic' behind ExecuteQuery, but I thought this may work due to the property mapping done behind the scenes. Any help is much appreciated.

有帮助吗?

解决方案

More recently, we've written dapper, which fits the original question beautifully:

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 works fine too.

其他提示

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

You could try passing in Tuple<int,string>, but I haven't tried this, and I'm not sure it will realise to map ctor arg 0 to col 0, etc.

I use code like in the question quite a bit, and creating a meaningful stub class usually isn't a problem, especially with automatically implemented properties.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top