c# - 使用自定义类转换 IEnumerable<dynamic>

标签 c# casting ienumerable dapper

我最近一直在使用 dapper,并希望创建一个动态方法,以便更轻松地使用 sql 选择内容。 这是我的代码:

类:

public class Method
{
    public static IEnumerable<dynamic> QueryAll(string table)
    { 
        dynamic dyn = table;
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbCon"].ToString());
        using (con)
        {
            string sql = String.Format("SELECT * FROM {0}", table);
            IEnumerable<dynamic> ie = con.Query<dynamic>(sql, null);
            return ie;
        }

    }
}

在这里调用函数:

IEnumerable<posts> = Method.QueryAll("posts");

它给我一个错误我无法将 IEnumerable dynamic 转换为 IEnumerable Models.Posts

我怎样才能让它工作。

最佳答案

从技术上讲,您可以只使用 IEnumerable.Cast -method 将从方法返回的每个实例转换为实际实例。

IEnumerable<posts> = Method.QueryAll("posts").Cast<posts>();

但是,如果您已经知道实际类型,为什么不在查询中使用它呢? dynamic应该小心处理,只有在你真的需要的时候,我怀疑这里是这种情况。例如,您可以将实际类型作为类型参数添加到方法中:

public static IEnumerable<T> QueryAll<T>(string table)
{ 
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbCon"].ToString());
    using (con)
    {
        string sql = String.Format("SELECT * FROM {0}", table);
        IEnumerable<T> ie = con.Query<T>(sql, null);
        return ie;
    }
}

现在可以这样调用了:

var result = Method.QueryAll<posts>("posts");

题外话Method是一个非常糟糕的类名,如posts还。你应该给你的类名来描述他们服务的目的和他们正在做的事情。此外,还有命名约定建议使用 PascalCase -类(class)名称 Posts .最后当你有一个 posts 的枚举时,我想这个类本身代表一个帖子,而不是很多,所以你实际上想要一个名为 Post 的类您可以将其存储到 IEnumerable<Post> 中.

关于c# - 使用自定义类转换 IEnumerable<dynamic>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821004/

相关文章:

c - printf 的意外输出

C++ 通过右引用传递混淆的函数

c - 为什么我没有收到将指针转换为 int 的警告?

c# - Database.Query 返回类型应该是 IEnumerable<dynamic>

c# - 链接的 IEnumerable 方法Where和Select比单独执行它们慢吗?

ienumerable - 使用 IEnumerable<T> 和 WebGet 序列化数据

c# - Unity C# 数组 - 如何克隆

c# - 使用 System.DirectoryServices.AccountManagement 时出现 DirectoryServicesCOMException

c# - 保持按钮位置与调整图像大小成比例

c# - 为什么.net 2.0 比 4.0 快