Query PostgreSQL with Npgsql and Entity Framework using unaccent

怎甘沉沦 提交于 2020-07-06 20:29:32

问题


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')

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.


回答1:


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

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

Example of database context:

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();
    }
}

Example of usage:

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

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



来源:https://stackoverflow.com/questions/36891063/query-postgresql-with-npgsql-and-entity-framework-using-unaccent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!