【问题标题】:how to prevent Entity-Framework to generate N'..' prefixed unicode strings?如何防止实体框架生成 N'..' 前缀的 unicode 字符串?
【发布时间】:2011-07-31 10:32:59
【问题描述】:

我使用 EF 4.1 代码优先,
问题是:EF 默认生成所有带有 N'..' 前缀的 unicode 字段。像这样 : exec sp_executesql N'SELECT ... FROM ... WHERE [Title] LIKE @p__linq__0 ESCAPE N''~''', N'@p__linq__0 nvarchar(4000)', @p__linq__0=N'%...%'

但它在某些字符上给我带来了一些问题。我想知道是否有办法防止 EF 添加 N 前缀?

【问题讨论】:

    标签: entity-framework entity unicode-string


    【解决方案1】:

    您可以将字符串包装在 http://msdn.microsoft.com/en-us/library/system.data.objects.entityfunctions.asnonunicode.aspx 中提到的 AsNonUnicode 方法中,这将生成普通字符串。

    【讨论】:

    • 是的,我知道。我想要一个更通用的解决方案,但似乎没有比 AsNonUnicode 更好的了 :-(
    【解决方案2】:

    另一种解决方案是使用 CommandInterceptors 并在执行之前修改生成的 sql 查询。

    我在使用 oracle 数据库和 ODP.net 提供程序时遇到了类似的问题。 AsNonUnicode 没有解决我的问题。

    EF 6 提供了在对数据库执行 ExecuteNonQuery、ExecuteScalar、ExecuteReader 操作之前和之后使用 IDbCommandInterceptor 拦截上下文的能力。您需要使用配置文件或基于代码的配置来配置拦截器。

    配置文件:

    <entityFramework>
        <interceptors>
          <interceptor type="EfSample.EfCommandInterceptor, EfSample">
          </interceptor>
        </interceptors>
    </entityFramework>
    

    基于代码的配置:

    public sealed class EntityFrameworkConfiguration : DbConfiguration
    {
         public EntityFrameworkConfiguration ()
         {
             this.AddInterceptor(new EfCommandInterceptor());
         }
    }
    

    如下图所示创建CommandInterceptor:

    public sealed class EfCommandInterceptor
        : DbCommandInterceptor
    {
        /// <summary>
        /// Called when Reader is executing.
        /// </summary>
        /// <param name="command"></param>
        /// <param name="interceptionContext"></param>
        /// <inheritdoc />
        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            if(command.CommandText.Contains("N''"))
            {
                command.CommandText = command.CommandText.Replace("N''", "''");
            }
    
            base.ReaderExecuting(command, interceptionContext);
        }
    }
    

    【讨论】:

    • 这解决了我的问题!但是,这种解决方案感觉并不好。这是绕过 Oracle 问题吗?
    • 另外,请注意此查询无法处理以下极端情况:SELECT N'Youssou N''Dour' FROM DUAL(对我们来说这不是问题,但请注意)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2019-05-30
    • 2014-09-12
    • 2011-01-10
    相关资源
    最近更新 更多