简体   繁体   English

使用unaccent使用Npgsql和Entity Framework查询PostgreSQL

[英]Query PostgreSQL with Npgsql and Entity Framework using unaccent

Is possible to use Npgsql and Entity Framework 6 for query PostgreSQL ignoring accents? 可以使用Npgsql和Entity Framework 6来查询PostgreSQL时忽略重音符号吗? In play SQL it's possible to use the unaccent extension and could be indexed with a index also based in unaccent: 在SQL中,可以使用unaccent扩展名,并且可以使用基于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. 在以前使用MySql的项目中,我可以使用诸如utf8_swedish_ci之类的排序规则不区分大小写的字母来解决此问题,但据我所知,PostgreSQL缺乏这种解决方案。

If you use the Codefirst approach, you should try to use EntityFramework.CodeFirstStoreFunctions . 如果使用Codefirst方法,则应尝试使用EntityFramework.CodeFirstStoreFunctions

  1. First add EntityFramework.CodeFirstStoreFunctions to your project 首先将EntityFramework.CodeFirstStoreFunctions添加到您的项目中
  2. Add a custom convention with unaccent to DbModelBuilder 添加自定义的公约与unaccent到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.*). 此解决方案与EntityFramework6.Npgsql (使用Npgsql 3. *)一起使用。
It doesn't work with Npgsql.EntityFramework (which uses Npgsql 2.*) 它不适用于Npgsql.EntityFramework (使用Npgsql 2. *)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM