在Update查询中使用SqlExpression中的SQL Server函数

时间:2021-04-09 00:10:31

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

在SubSonic 2.2版中,以下(特定于MSSQL)代码失败:

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.ToString()生成一个完全合法的SQL语句:

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

update.Execute() however fails with:

update.Execute()但失败了:

{"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?

是否有可能在表达式中使用sql server函数?

2 个解决方案

#1


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);

#2


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:

好的,我找到了一个解决方法 - 可以在InlineQuery之外使用SQL Server函数。诀窍是你不能使用使用TableColumn参数的“强类型”版本的SetExpression,而是传递列名字符串,如下所示:

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.

重要的部分是:SomeTable.Columns.SomeDateTime而不是SomeTable.SomeDateTimeColumn。

#1


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);

#2


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:

好的,我找到了一个解决方法 - 可以在InlineQuery之外使用SQL Server函数。诀窍是你不能使用使用TableColumn参数的“强类型”版本的SetExpression,而是传递列名字符串,如下所示:

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.

重要的部分是:SomeTable.Columns.SomeDateTime而不是SomeTable.SomeDateTimeColumn。