In Linq to Entity Query, When one data type is Integer and other is of type string then to avoid type mismatch problem, one cannot use Convert.ToInt32() Function with string parameter or .ToString() function with the integer parameter. It will give you the following error :
“LINQ to Entities does not recognize the method ‘System.String ToString()’ method, and this method cannot be translated into a store expression”.
eg:
Suppose we have to write an LINQ join query between two tables (say Table1 and Table2) based on Primary Key of Table1 (t1.Pk_Id [Long]) and foreign key of Table2 (t2.Fk_Id [String]).
DataContextClass contextObject = new DataContextClass();
var objData = (from t1 in contextObject.Table1
join t2 in contextObject.Table2 on t1.Pk_Id equals t2.Fk_Id where t1.ColumnName == … ….. ….. select new { …… …… }); To run this query efficiently the data type of Pk_Id column from both the table should match. But since t1.Pk_Id is of long type and t2.Fk_Id is of string type then it will result in build error.
|
To avoid this problem we can use StringConvert() method provided by SqlFunctions class with Entity Framework version 4 to convert any numeric value to String type.
eg:
using System.Data.Objects.SqlClient; DataContextClass contextObject = new DataContextClass();
var objData = (from t1 in contextObject.Table1 join t2 in contextObject.Table2 on SqlFunctions.StringConvert((double)t1.Pk_Id).Trim() equals t2.Fk_Id.Trim()
where t1.ColumnName == … ….. ….. select new { …… …… }); StringConvert function returns character data converted from numeric data. This memebr can be overloaded but there is no overload for int so you need to cast to a double or a decimal. SqlFunctions class is provided by System.Data.Objects.SqlClientnamespace. It Contains CLR methods that call functions in Database and can be used only LINQ to Entiy Quries. You cannot call this function directly. This function can only appear within a LINQ to Entities query.
For more details on SqlFunctions class and StringConvert function and its overloaded method, visit-
|