ServiceStack.OrmLite选择<>使用WITH CTE时抛出npgsql语法错误

时间:2014-04-03 07:00:21

标签: servicestack ormlite-servicestack npgsql

从错误中我认为这是Npgsql(see closed issue)的问题,但错误是使用OrmLite Select<>因为它改变了执行的sql。

问题:

  1. 除了不使用WITH CTE之外,OrmLite还有另一种解决此错误的方法吗?
  2. 是db.Select<>要使用错误的命令?
  3. 注意:WIT​​H CTE适用于OrmLite.Scalar

    Postgres WITH CTE:http://www.postgresql.org/docs/current/static/queries-with.html

    更新:问题似乎是OrmLite准备SQL语句而不是以" SELECT"开头。导致OrmLite将SQL视为" WHERE" PARAM。

    [Test]
    public void with_cte_ormlite_obj()
    {
        using (var db = DbConnection)
        {
            var sql = "WITH w_cnt AS (SELECT 5 AS cnt, 'me' AS name) SELECT cnt, name FROM w_cnt";
    
    // An exception of type 'Npgsql.NpgsqlException' occurred in Npgsql.dll
    // ERROR: 42601: syntax error at or near "WITH w_cnt"
    // Actual Exec Sql: 
    // SELECT "cnt", "name" FROM "my_with_cte_obj" WHERE WITH w_cnt AS (SELECT 5 AS cnt, 'me' AS name) SELECT cnt, name FROM w_cnt
    
            var cnt = db.Select<MyWithCteObj>(sql);
            var first = cnt.First();
            Assert.AreEqual(5, first.Cnt);
            Assert.AreEqual("me", first.Name);
        }
    }
    
    public class MyWithCteObj
    {
        public int Cnt { get; set; }
        public string Name { get; set; }
    }
    

1 个答案:

答案 0 :(得分:2)

db.Select<T>() API只能用于SQL SELECT 语句。

db.SqlList<T>() API应该用于非SELECT查询,例如:

using (var db = DbConnection)
{
    var cnt = db.SqlList<MyWithCteObj>(
        "WITH w_cnt AS (SELECT 5 AS cnt, 'me' AS name) SELECT cnt, name FROM w_cnt");
}

请参阅文档了解更多custom SQL APIs examples