有没有办法概括 petapoco select 查询

Is there a way to generalize petapoco select query

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

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函数中传递实体类型。对于每个 DB table,我们需要定义实体。在这种情况下,实体类型是<Employers>,代码是:

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

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

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.