1

I have a query like this in a SQL Server stored procedure:

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

I want its equivalent in Linq-to-entities inside C# so that GETDATE() be used. I don't want to use local client time and stuff like this. I want SQL Server time be the reference to be stored in the updateDate column

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
VSB
  • 9,825
  • 16
  • 72
  • 145

1 Answers1

0

These two options can help achieve your goal:

  1. Using a raw SQL in Entity Framework
  2. Calling a stored procedure with parameters

Let's see some code:

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

Note: you could use parameters instead of string interpolation for security reasons.

Here's an example with stored procedure and parameters.

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));
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pato
  • 462
  • 2
  • 4
  • 11