I need to update a row of alarms with Linq to SQL, which can contain over 100000 rows.
Which means that a simple update such as:
foreach (var alarm in Alarms)
{
alarm.Alarm_Ack_UTC = DateTime.UtcNow;
}
SubmitChanges();
gives me a SQL query of
SELECT [t0].[Alarm_ID], [t0].[Alarm_Application_Number], [t0].[Alarm_Ack_UTC], [t0].[Alarm_DateTime_UTC], [t0].[Alarm_Message_Number], [t0].[Username], [t0].[Runtime_Message], [t0].[Alarm_Application_Name], [t0].[Alarm_Application_Computer], [t0].[Alarm_GUID], [t0].[Alarm_Comments]
FROM [Alarms] AS [t0]
GO
-- Region Parameters
DECLARE @p0 Int = 1
DECLARE @p1 DateTime = '2012-03-16 11:56:25.850'
-- EndRegion
UPDATE [Alarms]
SET [Alarm_Ack_UTC] = @p1
WHERE [Alarm_ID] = @p0
GO
-- Region Parameters
DECLARE @p0 Int = 2
DECLARE @p1 DateTime = '2012-03-16 11:56:25.851'
-- EndRegion
UPDATE [Alarms]
SET [Alarm_Ack_UTC] = @p1
WHERE [Alarm_ID] = @p0
GO
-- Region Parameters
DECLARE @p0 Int = 3
DECLARE @p1 DateTime = '2012-03-16 11:56:25.851'
-- EndRegion
UPDATE [Alarms]
SET [Alarm_Ack_UTC] = @p1
WHERE [Alarm_ID] = @p0
GO
Repeated 100000 times, which is really slow, inefficient and unoptimized.
The real query is more advanced, and update more data, uses a .Where(a => a.Time != null) and other things.
But just to improve the query above, which could be replaced with the very efficient SQL query:
UPDATE [Alarms]
SET Alarm_Ack_UTC = GETUTCDATE()
GO
How can one achieve this with Linq to SQL? Or is it impossible?
You can’t do this with LINQ to SQL (or any other O/RM). They will always fetch an object from the database that you want to change and have a single update statement for that entity. If you change 10,000 entities, you will have at least 10,000 update statements.
If this is too slow, switch to a stored procedure or manual SQL statement in that case.