I’ve got a table that has a column where the codes are a string that starts with from 2 to 4 characters then may or may not have a space then it has a number. For example: KR123 or KS 23 or K23456. The following SQL Code on SQL Server 2008 will return just the number:
Select CONVERT(int, Reverse(LEFT(REVERSE(codefield),PATINDEX('%[a-z]%', REVERSE(codefield)) - 1)))
From Table1
This works great in SQL, but one of the programmers I work with wants to use LINQ to Entites to do the same thing. I tried this code in VB.Net just to see if I could get the index value of the reversed field from the first row:
Dim theResult = theContext.Table1.select(function(y)
System.Data.Objects.SQLClient.SQLFunctions.PatIndex("%[a-z]%", y.codefield.Reverse)
).FirstOrDefault
It compiles fine, but this gives me the error when it runs: LINQ to Entities does not recognize the method ‘System.Collections.Generic.IEnumerable1[System.Char] Reverse[Char](System.Collections.Generic.IEnumerable1[System.Char])’ method, and this method cannot be translated into a store expression.
If I remove the .Reverse, it works, but I need to be able to reverse the column data for the code to correctly work.
Can anyone figure out how to do the original select using LINQ to Entities?
Thanks,
NCGrimbo
If you need numbers why don’t you just match on the number instead of text – something like this:
(The 200 (or whatever number suites you – I wish there was Int.Max in T-SQL) is arbitrary just to not deal with calculating the length of the string – if the length is bigger than the string the whole substring starting at start position will be returned)
Now the query in Linq to Entities is pretty simple (sorry for using C#):
Note that Entity Framework will come up with the code calculating the string length. You can avoid it again by using the trick with the arbitrary big number like this:
Back to the original question – you can use Reverse but in a bit different way: