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
CodePudding user response:
Does this help you?
context.Students.Select (c => DateTime.Now);
is equal to:
SELECT GETDATE() AS 'Example'
FROM [dbo].[StudentTable]
CodePudding user response:
These two options can help achieve your goal:
Using a raw sql in entity framework.
Calling a store 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));