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

纵然是瞬间 提交于 2020-01-10 02:06:11

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5025702/how-to-work-with-objects-of-unknown-type-returned-from-datacontext-executequery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!