I have a table with an index on a nvarchar(MAX)-column by using CHECKSUM() as a computed column. SQL query can use this index by using a WHERE-clause with both the text value and its checksum.
How can a linq-to-sql query use this index?
I looked at sqlfunctions.checksum of linq object and How do I calculate a checksum on all columns in a row using LINQ and Entity Framework? and their answers, i.e SqlFunctions.Checksum("important") for a checksum of a single value.
But SqlFunctions.Checksum("important") throws the exception:
This function can only be invoked from LINQ to Entities
(this behaviour is exactly as is documented in the documentation for Checksum(string)).
In sqlserver the table can be defined via:
CREATE TABLE [Tags](
[TagId] [uniqueidentifier] NOT NULL PRIMARY KEY,
[Tag] [nvarchar](max) NOT NULL,
[TagHash] AS (checksum([Tag])) PERSISTED
)
and the index via:
CREATE INDEX [IX_Tags] ON [Tags] (
[TagHash] ASC
)
The following SQL query might use the index1:
SELECT * FROM [Tags]
WHERE [TagHash] = checksum('Important') AND
[Tag] = 'Important'
This query expression attempt in linqpad c# throws the NotSupportedException:
from tag in Tags
where SqlFunctions.Checksum("important") == tag.Hash &&
"important" == tag.Tag
select tag
How can the above query be constructed in link-to-sql without using link-to-entities only constructs like SqlFunctions.Checksum(string)?
1) It depends on the query optimizer.