使用unaccent使用Npgsql和Entity Framework查询PostgreSQL [英] Query PostgreSQL with Npgsql and Entity Framework using unaccent

查看:162
本文介绍了使用unaccent使用Npgsql和Entity Framework查询PostgreSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Npgsql和Entity Framework 6来查询PostgreSQL而忽略重音符号?在运行SQL时,可以使用unaccent扩展名,并可以使用基于unaccent的索引进行索引:

Is possible to use Npgsql and Entity Framework 6 for query PostgreSQL ignoring accents? In play SQL it's possible to use the unaccent extension and could be indexed with a index also based in unaccent:

select * from users where unaccent(name) = unaccent('João')

在以前使用MySql的项目中,我可以解决此问题仅使用诸如utf8_swedish_ci之类的排序规则重音不敏感的问题,但据我所知PostgreSQL缺少这种解决方案。

In previous projects using MySql I could solve this problem just using a collation accent insensitive like utf8_swedish_ci but PostgreSQL lacks this kind of solution as far as I know.

推荐答案

如果使用 Codefirst 方法,则应尝试使用 EntityFramework.CodeFirstStoreFunctions

If you use the Codefirst approach, you should try to use EntityFramework.CodeFirstStoreFunctions.


  1. First将EntityFramework.CodeFirstStoreFunctions添加到您的项目

  2. 将带有 unaccent 的自定义约定添加到DbModelBuilder

  3. 在查询中使用它。

  1. First add EntityFramework.CodeFirstStoreFunctions to your project
  2. Add a custom convention with unaccent to DbModelBuilder
  3. Use it in a query.

数据库上下文示例:

public class DatabaseContext : DbContext
{
    public DatabaseContext () : base("Context")
    {
        Database.SetInitializer<DatabaseContext>(null);
    }

    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("public");
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        /** Adding unaccent **/           
        modelBuilder.Conventions.Add(new CodeFirstStoreFunctions.FunctionsConvention<DatabaseContext>("public"));
    }

    [DbFunction("CodeFirstDatabaseSchema", "unaccent")]
    public string Unaccent(string value)
    {
        // no need to provide an implementation
        throw new NotSupportedException();
    }
}

用法示例:

var users = ctx.Users
               .Where(elem => ctx.Unaccent(elem.FirstName) == ctx.Unaccent("João"))
               .ToList();

重要提示:

此解决方案与 EntityFramework6.Npgsql (使用Npgsql 3. *)。
不适用于 Npgsql.EntityFramework (使用Npgsql 2。*)

Important notice:
This solution works with EntityFramework6.Npgsql (which uses Npgsql 3.*).
It doesn't work with Npgsql.EntityFramework (which uses Npgsql 2.*)

这篇关于使用unaccent使用Npgsql和Entity Framework查询PostgreSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆