tags:

views:

162

answers:

2

In SubSonic, version 2.2, the following (MSSQL-specific) code fails:

SqlQuery update = 
  new Update(SomeTable)
      .SetExpression(SomeTable.SomeDateTimeColumn).IsEqualTo("GETDATE()")
      .Where(SomeTable.IdColumn).IsEqualTo(id);

At this point update.ToString() produces a perfectly legal SQL sentence:

UPDATE [dbo].[SomeTable] SET [SomeDateTime]=GETDATE()
WHERE [dbo].[SomeTable].[ID] = @ID0

update.Execute() however fails with:

{"Failed to convert parameter value from a String to a DateTime."}
  at SubSonic.Update.Execute()

Is there any possibility to use sql server functions in expressions?

A: 

For the specific example you've posted you could just do the following:

SqlQuery update = new Update(SomeTable)
  .SetExpression(SomeTable.SomeDateTimeColumn).IsEqualTo(DateTime.Now)
  .Where(SomeTable.IdColumn).IsEqualTo(id);
Adam
Thanks for the quick answer :) The problem is that I need database server timestamp in expression. Actually, I'm doing some timestamp arithmetic, and as it seems InlineQuery seems to be my only option at the moment. Or a two-stage operation in transcation, I can obtain my value by a separate SQL (this works): DateTime dt = new InlineQuery().ExecuteScalar<DateTime>(String.Format("SELECT DATEADD(second,{0},GETDATE())", Math.Abs(timeout)));
holzbrenner
+3  A: 

Ok, I've found a workaround - it is possible to use SQL Server functions outside of InlineQuery. The trick is that you must not use "strongly typed" version of SetExpression that uses TableColumn parameter, but pass column name strings, like this:

SqlQuery update = 
  new Update(SomeTable)
      .SetExpression(SomeTable.Columns.SomeDateTime).IsEqualTo("GETDATE()")
      .Where(SomeTable.IdColumn).IsEqualTo(id);

The important part being: SomeTable.Columns.SomeDateTime instead of SomeTable.SomeDateTimeColumn.

holzbrenner
Never even thought to try this! Thanks!
ranomore