簡體   English   中英

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

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

可以使用Npgsql和Entity Framework 6來查詢PostgreSQL時忽略重音符號嗎? 在SQL中,可以使用unaccent擴展名,並且可以使用基於unaccent的索引進行索引:

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

在以前使用MySql的項目中,我可以使用諸如utf8_swedish_ci之類的排序規則不區分大小寫的字母來解決此問題,但據我所知,PostgreSQL缺乏這種解決方案。

如果使用Codefirst方法,則應嘗試使用EntityFramework.CodeFirstStoreFunctions

  1. 首先將EntityFramework.CodeFirstStoreFunctions添加到您的項目中
  2. 添加自定義的公約與unaccent到DbModelBuilder
  3. 在查詢中使用它。

數據庫上下文示例:

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. *)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM