Map custom database value function in Entity Framework

天大地大妈咪最大 提交于 2020-01-05 04:15:12

问题


I have a simple database function, which expects two strings as parameter and returns a string. I want to map this with entity framework. Similar to this question, I've created a simple function header:

[DbFunction("dbo", "StripCharacters")]
public static string StripCharacters(string input, string pattern = "^A-Z0-9") => throw new NotSupportedException();

Like in the linked post, I get the same error message, as soon as I try to use this method inside one of my queries. The exception message is:

Method System.String StripCharacters(System.String, System.String) in type DE.ZA.TrailerLoadingAssistant.Web.Models.DatabaseEntities cannot be translated into a LINQ to Entities store expression

await mapi.db.TrailerAutocompleteHelpers
    .Where(t => t.SearchString.Contains(DatabaseEntities.StripCharacters(userInput, "^A-Z0-9")))
    .ToListAsync();

Here's the database function:

CREATE FUNCTION [dbo].[StripCharacters]
(
    @String NVARCHAR(MAX), 
    @MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX) WITH SCHEMABINDING
AS
BEGIN
    SET @MatchExpression =  '%['+@MatchExpression+']%'

    WHILE PatIndex(@MatchExpression, @String) > 0
        SET @String = Stuff(@String, PatIndex(@MatchExpression, @String), 1, '')

    RETURN @String

END

How can I solve this problem?


回答1:


I actually made two mistakes. First off, you must add a function declaration to your EDMX file by hand:

<Function Name="StripCharacters" ReturnType="nvarchar" Schema="dbo" >
  <Parameter Name="String" Mode="In" Type="nvarchar" />
  <Parameter Name="MatchExpression" Mode="In" Type="varchar" />
</Function>

Secondly, the first parameter of the DbFunction attribute must not be the schema name of your database, but the Entity Framework model namespace. This can be found in the EDMX file again:

<Schema Namespace="MyApplicationModel.Store" ...>

The correct attribute would be:

[DbFunction("MyApplicationModel.Store", "StripCharacters")]


来源:https://stackoverflow.com/questions/58135042/map-custom-database-value-function-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!