How to run a function when querying a data entity using Entity Framework?
使用Entity Framework查询数据实体时如何运行函数?
var name = "First name";
// it throws exception here
var result = contactRepository.Query.FirstOrDefault(x => SanitizeUserInput(x.Name) == name);
public static string SanitizeUserInput(string value)
{
if (string.IsNullOrEmpty(value))
return string.Empty;
var htmlDecodedValue = HttpUtility.HtmlDecode(value);
return Regex.Replace(htmlDecodedValue ?? string.Empty, "<.*?>", string.Empty);
}
Query is of type IQueryable.
查询的类型为IQueryable。
I get the below error:
我得到以下错误:
LINQ to Entities does not recognize the method 'System.String SanitizeUserInput(System.String)' method, and this method cannot be translated into a store expression.
LINQ to Entities无法识别方法'System.String SanitizeUserInput(System.String)'方法,并且此方法无法转换为存储表达式。
1 个解决方案
#1
1
Entity Framework works following way - it translates expression tree into SQL text query, and then executes query using old good ADO.NET. Custom functions cannot be translated into SQL by Entity Framework provider. You can run custom function only in-memory:
实体框架按以下方式工作 - 它将表达式树转换为SQL文本查询,然后使用旧的好的ADO.NET执行查询。实体框架提供程序无法将自定义函数转换为SQL。您只能在内存中运行自定义功能:
var result = contactRepository.Query.AsEnumerable()
.FirstOrDefault(c => SanitizeUserInput(c.Name) == name);
This will generate SQL query for fetching all data from database and execute it. Then you will enumerate results reading DataReader rows one by one, mapping data to your entities and executing SanitizeUserInput
method until condition is met.
这将生成SQL查询以从数据库中获取所有数据并执行它。然后,您将枚举逐个读取DataReader行的结果,将数据映射到您的实体并执行SanitizeUserInput方法,直到满足条件。
#1
1
Entity Framework works following way - it translates expression tree into SQL text query, and then executes query using old good ADO.NET. Custom functions cannot be translated into SQL by Entity Framework provider. You can run custom function only in-memory:
实体框架按以下方式工作 - 它将表达式树转换为SQL文本查询,然后使用旧的好的ADO.NET执行查询。实体框架提供程序无法将自定义函数转换为SQL。您只能在内存中运行自定义功能:
var result = contactRepository.Query.AsEnumerable()
.FirstOrDefault(c => SanitizeUserInput(c.Name) == name);
This will generate SQL query for fetching all data from database and execute it. Then you will enumerate results reading DataReader rows one by one, mapping data to your entities and executing SanitizeUserInput
method until condition is met.
这将生成SQL查询以从数据库中获取所有数据并执行它。然后,您将枚举逐个读取DataReader行的结果,将数据映射到您的实体并执行SanitizeUserInput方法,直到满足条件。