Question

I'm trying to run update/select in a single statement, using a query similar to this:

UPDATE TOP(1) myTable SET blah = 'meh' OUTPUT INSERTED.*

Query itself works no problems, however I'm having hard time figuring out how to run it with OrmLite.

I've tried these methods:

QuerySingle, Select, Query - these are checking a query string, and if query doesn't start with "select" they treat sql I pass as a where clause, so in my case the query that goes to the server is actually broken (something like 'select blah Update....')

GetList(sql).SingleOrDefault() - throws 'Unable to cast object of type 'System.Int32' to type MyType'. Not quite sure what's wrong here.

Is there a way to run a raw sql and have OrmLite parse the results ?

Was it helpful?

Solution

Solved that by using SqlReader.

  using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    var reader = command.ExecuteReader();
                    var obj = reader.ConvertTo<MyObject>();
                }
            }

basically. ServiceStack has a handy converter from sqlreader to a concrete type.

OTHER TIPS

I like this (no need to create SqlCommand, just use IDbConnection _db)

ProjectTotals lastAmendments = _db.Exec<ProjectTotals>(new Func<IDbCommand, ProjectTotals>(delegate(IDbCommand com)
            {
                com.CommandText = @";WITH cte AS
(
   SELECT *,ROW_NUMBER() OVER (PARTITION BY BaseInvoiceId ORDER BY Id DESC) AS rn
   FROM PzuInvoice WHERE BaseInvoiceId is not null AND ProjectId = {0}
)
SELECT sum(TotalValue),sum(MarginPlan) [Margin], count(*) [Count]
FROM cte
WHERE rn = 1".Fmt(_invoice.ProjectId);

                var reader = com.ExecuteReader();
                return reader.ConvertTo<ProjectTotals>();

            }));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top