Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing SQL Server's CONTAINS() as a model defined function

I am trying to import SQL Server's CONTAINS() function in my Entity Framework model so that I can use it in my LINQ queries.

I have added this to my EDM:

<Function Name="FullTextSearch" ReturnType="Edm.Boolean">     <Parameter Name="Filter" Type="Edm.String" />     <DefiningExpression>         CONTAINS(*, Filter)     </DefiningExpression> </Function> 

Add created my method stub:

[EdmFunction("MyModelNamespace", "FullTextSearch")] public static bool FullTextSearch(string filter) {     throw new NotSupportedException("This function is only for L2E query."); } 

I try to call the function like this:

from product in Products where MyModel.FullTextSearch("FORMSOF(INFLECTIONAL, robe)") select product 

The following exception is raised:

The query syntax is not valid. Near term '*' 

I realize that the function I defined is not directly linked to the entity set being queried so that could also be a problem.

Is there any way to pull this off?

like image 721
Xavier Poinas Avatar asked Jan 26 '12 09:01

Xavier Poinas


People also ask

What is user defined function in SQL Server?

Like functions in programming languages, SQL Server user-defined functions are routines that accept parameters, perform an action, such as a complex calculation, and return the result of that action as a value. The return value can either be a single scalar value or a result set.


1 Answers

The function you have defined above uses Entity SQL, not Transact SQL, so I think the first step is to figure out whether CONTAINS(*,'text') can be expressed in Entity SQL.

Entity SQL doesn't support the * operator as described here: http://msdn.microsoft.com/en-us/library/bb738573.aspx and if I try

entities.CreateQuery<TABLE_NAME>("select value t from TABLE_NAME as t where CONTAINS(*, 'text')"); 

I get the same error you got above. If I try to explicitly pass the column it works:

entities.CreateQuery<TABLE_NAME>("select value t from TABLE_NAME as t where CONTAINS(t.COLUMN_NAME, 'text')"); 

But when I look at the SQL it translated it to a LIKE expression.

ADO.NET:Execute Reader "SELECT  [GroupBy1].[A1] AS [C1] FROM ( SELECT      COUNT(1) AS [A1]     FROM [dbo].[TABLE_NAME] AS [Extent1]     WHERE (CASE WHEN ([Extent1].[COLUMN_NAME] LIKE '%text%') THEN cast(1 as bit) WHEN ( NOT ([Extent1].[COLUMN_NAME] LIKE '%text%')) THEN cast(0 as bit) END) = 1 )  AS [GroupBy1]" 

If you cannot express the query using Entity SQL you'll have to use a Stored Procedure or other mechanism to use Transact SQL directly.

like image 87
MichaC Avatar answered Nov 05 '22 10:11

MichaC