如何处理DataContext.ExecuteQuery返回的未知类型的对象 [英] How to work with objects of unknown type returned from DataContext.ExecuteQuery

查看:219
本文介绍了如何处理DataContext.ExecuteQuery返回的未知类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,随着C#4.0中动态关键字的到来,我希望能够找到一个更好的解决方案来处理由 DataContext.ExecuteQuery 返回的类型的问题选择任意列。

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.

过去我已经创建了一个新类型来保存这样一个查询的结果,或者使用了描述在这个SO文章。所以现在我可以在一个运行在.NET 4.0下的新项目上进行工作,我用一种动态类型来研究一个不那么痛苦的方式来完成同样的事情。

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 ) );        
}

在运行时抛出异常,因为动态属性CustomerID不存在目的。所以,由于我在这个动态关键字的经验是没有(一篇文章/博客文章或两篇,没有真实的经验),我希望有人在这里可以让我知道,如果我想在这里做的甚至是可能的。我可能高估了ExecuteQuery后面的魔术的数量,但是我认为这可能是因为在幕后完成的属性映射。非常感谢任何帮助。

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.

推荐答案

最近,我们写了 dapper ,它适合原来的问题:

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 ) );        
}

它允许参数等,并且有一个(首选)类型的API通过查询< T> - 但动态 API工作正常。

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

这篇关于如何处理DataContext.ExecuteQuery返回的未知类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆