[英]Interception not working as expected with Entity Framework 6
I'm trying to follow the interception example shown here to get it working with EF 6 but running into a problem with the function RewriteFullTextQuery
as shown in Figure 1. The interception seems to work but it does not actually execute the logic in the for
loop of the RewriteFullTextQuery
method because the cmd.Parameters.Count
is always zero. 我正在尝试遵循此处显示的拦截示例,以使其与EF 6配合使用,但遇到函数RewriteFullTextQuery
的问题,如图1所示。该拦截似乎有效,但实际上并未执行for
循环中的逻辑RewriteFullTextQuery
方法的功能,因为cmd.Parameters.Count
始终为零。 Furthermore the cmd.CommandText
property seems to be displaying the correct SQL query which I take as another piece of evidence that the interception is working correctly. 此外, cmd.CommandText
属性似乎正在显示正确的SQL查询,我将其作为另一证据证明拦截工作正常。
Figure 1: RewriteFullTextQuery Code Excerpt 图1:RewriteFullTextQuery代码摘录
public static void RewriteFullTextQuery(DbCommand cmd)
{
string text = cmd.CommandText;
for (int i = 0; i < cmd.Parameters.Count; i++)
{
DbParameter parameter = cmd.Parameters[i];
if (parameter.DbType.In(DbType.String, DbType.AnsiString, DbType.StringFixedLength, DbType.AnsiStringFixedLength))
{
The RewriteFullTextQuery function is being called by the ReaderExecuting
function shown in Figure 2 which gives it the command argument that is causing all the trouble. 图2所示的ReaderExecuting函数正在调用ReaderExecuting
函数,该函数为其提供了引起所有麻烦的命令参数。
Figure 2: ReaderExecuting Function 图2:ReaderExecuting功能
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
RewriteFullTextQuery(command);
}
Even though my code isn't exactly the same as the example, the interception seems to be working so it is making me wonder what conditions is it that will populate the command to have a Parameters.Count
of more than zero? 虽然我的代码是不完全一样的例子中,拦截似乎是工作,所以它是让我知道什么样的条件是将填充命令有Parameters.Count
的大于零?
It works only if you pass the parameter to the query as a variable. 仅当您将参数作为变量传递给查询时,它才有效。 If you use a literal EF won't use parameters. 如果使用文字EF,则不会使用参数。
I mean, this won't generate any parameter 我的意思是,这不会生成任何参数
context.Notes.Where(_ => _.NoteText == "CompareValue").Count();
This will 这将
string compareValue = "CompareValue";
context.Notes.Where(_ => _.NoteText == compareValue).Count();
It turns out that it is because of the way Entity Framework generates the SQL. 事实证明,这是由于实体框架生成SQL的方式所致。 If you pass in a string literal as your search value to your LINQ statement it does not generate a SQL that makes use of a parameter. 如果将字符串文字作为搜索值传递给LINQ语句,则它不会生成使用参数的SQL。 But if you pass in your search value as a variable, it will generate the SQL that utilizes a parameter. 但是,如果您将搜索值作为变量传递,它将生成利用参数的SQL。 A solution (for dynamic queries) and more details can be found on this blog . 一个解决方案(用于动态查询)和更多详细信息可以在此Blog上找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.