I'm trying to make efficient use of a UPDATE
query while updating multiple records (instead of looping for every Id
).
I have this simple method:
public static async Task EfficientlyUpdateSentTimeforSomeTicketsAsync(List<int> Ids)
{
var parameters = Ids.Select((id, index) => new SqlParameter(string.Format("@p{0}", index), id));
var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName));
var query = string.Format("Update [TicketQueueTable] Set SentDatetime = {1} WHERE TicketQueueID IN ({0})", parameterNames, DateTime.Now);
try
{
using (var db = GetDbContext())
{
var affectedRows = await db.Database.ExecuteSqlCommandAsync(query, parameters.ToArray());
}
}
catch (Exception ex)
{
await LogErrorAsync(ex);
throw ex;
}
}
I took help from this SO question: https://stackoverflow.com/a/43969812/8644294 but I'm unable to make this work. It hits me with exception that says:
Incorrect syntax near '2'
For simplicity, the Ids that I'm sending for now is new List<int>() { 1, 2 }
.
Thank you for your time.