如何处理从 DataContext.ExecuteQuery 返回的未知类型的对象
- 作者: 祐边
- 来源: 51数据库
- 2022-12-13
问题描述
因此,随着 C# 4.0 中 dynamic 关键字的出现,我希望能够找到更好的解决方案来解决选择任意列时由 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.
所以,我试了一下:
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 属性不存在.因此,由于到目前为止我对 dynamic 关键字的经验为零(一两篇文章/博文,没有真正的经验),我希望这里有人可以让我知道我在这里尝试做的事情是否可行.我可能高估了 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 ) );
}
它允许参数等,并且有一个通过 Query
It allows parameters etc, and there is a (preferred) typed API via Query<T> - but the dynamic API works fine too.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
