Usage of SQL Server function in SqlExpression in Update query
-
05-07-2019 - |
Question
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?
Solution
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);
OTHER TIPS
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
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow