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?
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With