【问题标题】:C# store SQL Server date in LINQ date field like GETDATE() in SQL ServerC# 将 SQL Server 日期存储在 LINQ 日期字段中,如 SQL Server 中的 GETDATE()
【发布时间】:2022-01-02 12:11:18
【问题描述】:

我在 SQL Server 存储过程中有这样的查询:

UPDATE StudentTable 
SET isUpdate = 1, updateDate = GETDATE()

我希望它在 C# 中的 Linq-to-entities 中等效,以便使用 GETDATE()。我不想使用本地客户端时间和类似的东西。我希望 SQL Server 时间是要存储在 updateDate 列中的参考

【问题讨论】:

  • 你的意思是使用DateTime.Now
  • 哪个 EF 版本?

标签: c# sql-server entity-framework linq-to-entities


【解决方案1】:

这两个选项可以帮助您实现目标:

  1. 在实体框架中使用原始 SQL
  2. 使用参数调用存储过程

让我们看一些代码:

// your input from a secure source
int input = 1; 

// To add where and more lines you can use concatenation or string builder
string sql = $"UPDATE StudentTable SET isUpdate = {input}, 
updateDate = GETDATE()";

await db.Database.ExecuteSqlRawAsync(sql);

注意:出于安全原因,您可以使用参数而不是字符串插值。

这是一个包含存储过程和参数的示例。

using Microsoft.EntityFrameworkCore;
using Microsoft.Data.SqlClient;
//...

int input = 1;
long id = 10;

db.Database.ExecuteSqlRaw("exec [schema].[myCustomSP] @isUpdate, @id", 
  new SqlParameter("isUpdate", input), 
  new SqlParameter("id", id));

【讨论】:

    猜你喜欢
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多