c# - 有没有办法概括 petapoco 选择查询

标签 c# petapoco

我正在尝试使用 PetaPoco ORM 从 MySQL 表获取数据。下面是仅获取一条记录的示例代码:

public void ShowEmployerDetails()
        {
            using (var db = new PetaPoco.Database ("mysql_mydb")) {
                try {
                    var employers = db.Query <Employers> ("SELECT * FROM Employer WHERE id = 123456789");
                    foreach(var e in employers) {
                        return e.EmployerName;
                    }
                } catch (Exception ex) {
                    log.Error (ex.Message);
                }
            }
        }

db.Query函数中需要传递实体类型。对于每个数据库表,我们需要定义实体。在本例中,实体类型为<Employers>,代码如下:

public class Employers
    {
        public int id { get; set; }
        public string EmployerName { get; set; }
    }

有什么方法可以概括上面的选择查询吗?例如,我计划使用单个查询获取输出,例如:

PetaPocoQueryEntities <Employers>.GetDataFromEntities ("SELECT * FROM Employer WHERE id = 123456789", "EmployerName");

查询可能如下所示,其中实体类型可以作为通用类型 T 传递,并想知道是否有某种方法可以动态提供列名称和获取列值:

public static class PetaPocoQueryEntities <T> 
    {
        public static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static T GetDataFromEntity (string sqlQuery, string colName )
        {
            using (var db = new PetaPoco.Database ("mysql_mydb")) {
                try {
                    var entityResults = db.Query<T> (sqlQuery);
                    foreach (var result in entityResults) {
                        log.Info(colName + " value is " + result.colName);
                    }
                } catch (Exception ex) {
                    log.Error (ex.Message);
                }
                return colName;
            }
        }
}

请帮忙。

最佳答案

There is need to pass the entity type in db.Query function

简短的回答 - 是的。 PetaPoco 使用此信息将查询中的数据正确映射回实体

Is there any way that we can generalize the above select query also? For instance, I'm planning to get output using single query like:

是的,你可以安装这个。 This integration test should get you started.

关于c# - 有没有办法概括 petapoco 选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43366108/

相关文章:

c# - 解析网页中的超链接

asp.net-mvc-3 - 使用 PetaPoco 实现存储库模式

petapoco - 实现 IMapper 接口(interface)

c# - Petapoco tt 文件错误

c# - TargetFramework 更改后如何维护特定于语言的评论

c# - 使用多个提交按钮

architecture - 如何在 3 层应用程序中构造 PetaPOCO 生成的代码?

c# - 动态查询的最佳选择?

c# - Nuget 迁移的 Svn 外部 - 关注点

c# - 如何从其隐藏代码访问资源字典中的控件?