在 Entity Framework 中映射自定义数据库值函数
Map custom database value function in Entity Framework
我有一个简单的数据库函数,需要两个字符串作为参数,returns 一个字符串。我想用 entity framework 映射它。类似于 this question,我创建了一个简单的函数头:
[DbFunction("dbo", "StripCharacters")]
public static string StripCharacters(string input, string pattern = "^A-Z0-9") => throw new NotSupportedException();
就像在链接 post 中一样,当我尝试在我的一个查询中使用此方法时,我收到了相同的错误消息。异常消息是:
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();
这是数据库函数:
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
我该如何解决这个问题?
其实我犯了两个错误。首先,您必须手动向 EDMX 文件添加函数声明:
<Function Name="StripCharacters" ReturnType="nvarchar" Schema="dbo" >
<Parameter Name="String" Mode="In" Type="nvarchar" />
<Parameter Name="MatchExpression" Mode="In" Type="varchar" />
</Function>
其次,DbFunction
属性的第一个参数不能是你数据库的schema名称,而是Entity Framework模型命名空间。这又可以在EDMX文件中找到:
<Schema Namespace="MyApplicationModel.Store" ...>
正确的属性应该是:
[DbFunction("MyApplicationModel.Store", "StripCharacters")]
我有一个简单的数据库函数,需要两个字符串作为参数,returns 一个字符串。我想用 entity framework 映射它。类似于 this question,我创建了一个简单的函数头:
[DbFunction("dbo", "StripCharacters")]
public static string StripCharacters(string input, string pattern = "^A-Z0-9") => throw new NotSupportedException();
就像在链接 post 中一样,当我尝试在我的一个查询中使用此方法时,我收到了相同的错误消息。异常消息是:
Method
System.String StripCharacters(System.String, System.String)
in typeDE.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();
这是数据库函数:
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
我该如何解决这个问题?
其实我犯了两个错误。首先,您必须手动向 EDMX 文件添加函数声明:
<Function Name="StripCharacters" ReturnType="nvarchar" Schema="dbo" >
<Parameter Name="String" Mode="In" Type="nvarchar" />
<Parameter Name="MatchExpression" Mode="In" Type="varchar" />
</Function>
其次,DbFunction
属性的第一个参数不能是你数据库的schema名称,而是Entity Framework模型命名空间。这又可以在EDMX文件中找到:
<Schema Namespace="MyApplicationModel.Store" ...>
正确的属性应该是:
[DbFunction("MyApplicationModel.Store", "StripCharacters")]