Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle Entity Framework - Call custom function (EDIT_DISTANCE)

I am using Entity Framework 6 and Oracle Database 11g (ODP.NET Manage Driver).

How to call UTL_MATCH.EDIT_DISTANCE function in LINQ query?

like image 559
Dolfik Avatar asked Aug 28 '15 13:08

Dolfik


People also ask

How do you call a function in Entity Framework?

Step 1: Create an entity class which inherits “DbContext” class. Step 2: The following is the structure of the database with table and stored procedure. Step 3: Create a class to store the returned tabular value. Step 4: Create an object for the entity above and method to call a function.

How do you call a table valued function in Entity Framework?

Step 1 − Select the Console Application from the middle pane and enter TableValuedFunctionDemo in the name field. Step 2 − In Server explorer right-click on your database. Step 3 − Select New Query and enter the following code in T-SQL editor to add a new table in your database.


2 Answers

There is an awesome Library to help with mapping Database functions and Stored Procedures to Entity Framework.

Install the Nuget package

- Install-Package EntityFramework.Functions

Create Extension Methods for functions:

public static class OracleFunctions
{
   [Function(FunctionType.BuiltInFunction, "TO_NUMBER")]
   public static int? ToNumber(this string value) => Function.CallNotSupported<int?>();
}

Map it on your EntityFramework Context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Conventions.Add(new FunctionConvention(typeof(OracleFunctions)));
}

Call your newly mapped "ToNumber()" function in your LINQ queries:

.FirstOrDefault(p => p.Id == "209706".ToNumber());

And bobs your Uncle.

Unfortunately, for Oracle functions that resides in a different schema, like UTL_MATCH.EDIT_DISTANCE it will not work. You are supposed to be able to set the schema, but it seems like it is not currently working with Oracle or something. But for other fucntions like SOUNDEX etc. this should work fine.

You can read the Documentation for EntityFramework.Functions here

like image 139
Gerrie Pretorius Avatar answered Sep 28 '22 04:09

Gerrie Pretorius


I agree with Gerrie Pretorius and if you used database first model , you must add a function to edmx file like below

   <Function Name="TO_NUMBER" Aggregate="false" BuiltIn="true" NiladicFunction="false" IsComposable="true" ParameterTypeSemantics="AllowImplicitConversion" ReturnType="number">
          <Parameter Name="valueStr" Type="varchar" Mode="In" />
        </Function>

Then add a static function to OracleFunctions class like below

[EdmFunction("Model.Store", "TO_CHAR")]
public static int? ToNumber(this string value) {
    throw new NotSupportedException("this function is not supported");
}

After that you can use ToNumber function freely.

like image 23
Mehmet Emin Yalçın Avatar answered Sep 28 '22 06:09

Mehmet Emin Yalçın